Tag: unique ptr

为什么我不能push_back一个unique_ptr成vector?

这个程序有什么问题? #include <memory> #include <vector> int main() { std::vector<std::unique_ptr<int>> vec; int x(1); std::unique_ptr<int> ptr2x(&x); vec.push_back(ptr2x); //This tiny command has a vicious error. return 0; } 错误: $ g++ -std=gnu++0x main.cpp In file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c+ +/mingw32/bits/c++allocator.h:34:0, from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c+ +/bits/allocator.h:48, from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c+ +/memory:64, from main.cpp:6: c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: I n member function 'void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp […]

make_unique和完美的转发

为什么标准C ++ 11库中没有std::make_unique函数模板? 我发现 std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3)); 有点冗长。 以下不会更好吗? auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3); 这隐藏了new很好,只提到一次类型。 无论如何,这是我尝试执行make_unique : template<typename T, typename… Args> std::unique_ptr<T> make_unique(Args&&… args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)…)); } 我花了相当长的时间才得到std::forward东西来编译,但我不确定是否正确。 是吗? std::forward<Args>(args)…是什么意思? 编译器做了什么?

如何将unique_ptr参数传递给构造函数或函数?

我新移动C ++ 11中的语义,我不知道如何处理构造函数或函数中的unique_ptr参数。 考虑这个引用自身的类: #include <memory> class Base { public: typedef unique_ptr<Base> UPtr; Base(){} Base(Base::UPtr n):next(std::move(n)){} virtual ~Base(){} void setNext(Base::UPtr n) { next = std::move(n); } protected : Base::UPtr next; }; 这是我应该如何编写函数采取unique_ptr参数? 我需要在调用代码中使用std::move吗? Base::UPtr b1; Base::UPtr b2(new Base()); b1->setNext(b2); //should I write b1->setNext(std::move(b2)); instead?

是否需要知道T的完整定义的std :: unique_ptr <T>?

我有一些代码,如下所示: #include <memory> class Thing; class MyClass { std::unique_ptr< Thing > my_thing; }; 如果我将这个头文件包含在一个不包含Thing类型定义的cpp中,那么这个不会在VS2010-SP1下编译: 1> C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ VC \ include \ memory(2067):error C2027:使用未定义的类型'Thing' 用std::unique_ptr std::shared_ptr替换std::unique_ptr并编译。 所以,我猜测这是当前VS2010 std::unique_ptr的实现,需要完整的定义,而且完全依赖于实现。 还是呢? 有没有什么标准的要求,使std::unique_ptr的实现不可能只与前向声明一起工作? 这感觉很奇怪,因为它只应该指向Thing ,不是吗?