对于已弃用的 std::auto_ptr,c++11 标准的等效项是什么?
What's c++11 standard's equivalent for the deprecated std::auto_ptr?
我有一些代码使用std::auto_ptr
,并在编译时对不推荐使用的std::auto_ptr
(Suse Linux 12.2上的GCC 4.7.1)发出丑陋的警告。
因此,我尝试了以下方法(因为我找到了一些来源,认为std::unique_ptr
应该是适当的等价物)
template<typename T>
struct AutoPtr
{
#ifdef COMPILE_FOR_CX11
typedef std::unique_ptr<T> Type;
#else
typedef std::auto_ptr<T> Type;
#endif
};
并用AutoPtr<T>::Type
替换了对std::auto_ptr<T>
的任何引用,但在使用此选项时出现编译错误。
我很确定我想在这些代码中使用类似std::auto_ptr
的东西,我知道它的罪魁祸首和不足。当使用std::unique_ptr
时,我得到的错误似乎与构造问题有关。
附带说明:用于构造的最后一个类是T
的继承类型,代码看起来像:
class MockClass;
class Client
{
public:
Client();
Client(const Client& rhs);
private:
mutable AutoPtr<MockClass>::Type embeddedMock;
};
Client::Client()
: embeddedMock(new ::testing::NiceMock<MockClass>())
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Getting errors here!
{
}
Client::Client(const Client& rhs)
: embeddedMock(rhs.embeddedMock)
{
}
那么,我可以在这里使用c++11集合中的什么是完全兼容的智能指针呢?
unique_ptr
是auto_ptr
的C++11替换工具。然而,这并不是一个简单的替换,因为auto_ptr
在复制语义上具有所有权转移,而unique_ptr
强制您显式地转移所有权。当你有这样的东西时:
auto_ptr<Foo> x(new Foo());
// ...
auto_ptr<Foo> y = x;
// ...
bar( y ); // copies y into bar(), transferring ownership
要使用unique_ptr
,您需要将move()
添加到所有权转移站点:
unique_ptr<Foo> x(new Foo());
// ...
unique_ptr<Foo> y = move(x);
// ...
bar( move(y) );
编辑:
如果不知道你会遇到什么特定的错误,很难判断你的默认构造函数为什么无法编译。但是,除非添加了move
,否则副本构造函数应该无法使用unique_ptr
进行编译。
相关文章:
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- C++11 标准是否保证零值有符号整数的一元减号为零?
- 是否可以仅使用标准 c++/c++11 实现不带"sleep"的计时器?
- 目标c是否需要一个标准来定义像c++11这样的内存模型
- 使用C++11标准的哪些规则来确定({..})中表达式的类型
- 使用标准库在 c++11 中使用 std::tie 提取嵌套在元组中的元组
- C++11:标准::result_of<>模板参数与标准::函数<>
- 如何按降序对标准数组进行排序 - C++ 11.
- 在 C++11 之前的标准下使用 string::c_str() 和 data()
- 在 C++11 标准中,为什么要依赖 char 类型实现?
- C++11 标准中的哪一部分规定了基元数据类型大小之间的相对顺序?
- 标准C++11是否保证std::async(std::launch::asyncfunc)在单独的线程中启动func
- 如何在标准C 11中制作共享_lock或upgrade_lock
- 事实上的标准 C++11 编码风格
- 在标准(C++11)中,有人说余数运算符只适用于积分类型
- 标准 C++11 是否保证"易失性原子<T>"同时具有语义(易失性 + 原子)?
- 新标准c++11禁止复制构造函数
- 标准C++11是否保证high_resolution_clock测量实时性(非CPU周期)