make_unique and perfect forwarding

Why is there no std::make_unique function template in the standard C++11 library? I find std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3)); a bit verbose. Wouldn’t the following be much nicer? auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3); This hides the new nicely and only mentions the type once. Anyway, here is my attempt at an implementation of make_unique: … Read more

std::unique_ptr with an incomplete type won’t compile

I’m using the pimpl-idiom with std::unique_ptr: class window { window(const rectangle& rect); private: class window_impl; // defined elsewhere std::unique_ptr<window_impl> impl_; // won’t compile }; However, I get a compile error regarding the use of an incomplete type, on line 304 in <memory>: Invalid application of ‘sizeof‘ to an incomplete type ‘uixx::window::window_impl‘ For as far as … Read more

Why can I not push_back a unique_ptr into a vector?

What is wrong with this program? #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; } The error: 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: In member function ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = std::unique_ptr<int>, … Read more

Is std::unique_ptr required to know the full definition of T?

I have some code in a header that looks like this: #include <memory> class Thing; class MyClass { std::unique_ptr< Thing > my_thing; }; If I include this header in a cpp that does not include the Thing type definition, then this does not compile under VS2010-SP1: 1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\memory(2067): error C2027: use … Read more

How do I pass a unique_ptr argument to a constructor or a function?

I’m new to move semantics in C++11 and I don’t know very well how to handle unique_ptr parameters in constructors or functions. Consider this class referencing itself: #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; }; Is … Read more