Unique_ptr property, private copy constructor, and move constructor

Given the base class for several derived classes, the goal was to create a wrapper class that allowed the STL container to see objects with the base interface, an event, although different derived classes could actually be added to the container. (See Extracting data from a heterogeneous std :: list ).

After some involvement, I came up with a new derived class that was a wrapper around the unique_ptr base class. However, the move constructor confuses me.

 class Base { friend class BaseWrapper; virtual Base * clone () const = 0; public: virtual ~Base () {} //... public interface }; class Derived : public Base { //... specific members for derived class Base * clone () const { return new Derived(*this); } public: //... implement public interface }; class BaseWrapper : public Base { std::unique_ptr<Base> ptr_; Base * clone () const { return ptr_->clone(); } public: BaseWrapper (const Base &b) : ptr_(b.clone()) {} //... implement public interface by forwarding to ptr_ }; typedef std::list<BaseWrapper> BaseList; int main () { BaseList l; l.push_back(Derived()); } 

This does not compile with g ++ 4.7.2 .

Now, to use BaseWrapper , I can implement a public move constructor as follows:

  BaseWrapper (BaseWrapper &&bw) { ptr_.swap(bw.ptr_); } 

And it works great . But, if I make it private, it will not compile .

However, I found that instead of the above, I can instead create a private copy constructor (making it publicly available, of course):

  BaseWrapper (BaseWrapper &bw) { ptr_.swap(bw.ptr_); } 

Can someone tell me if this should work, and why or why not? If it should work, why can't I make the move constructor private?

You can follow this link to the toy program illustrating the above in a more complete way.

+4
source share
1 answer

[deleted erroneous diagnostics]

It really compiles on gcc 4.8. It seems that gcc 4.7 accepts BaseWrapper (const Base &) as the copy constructor (this is actually not the case) and implicitly removes the move constructor (which would be the expected behavior if it really were the copy constructor).

+4
source

All Articles