Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does push_back succeed on a struct containing a unique_ptr unless that struct has a custom destructor?

Tags:

c++

c++11

stl

The following code compiles if and only if I remove Foo's custom destructor.

struct Foo {
    std::unique_ptr <int> bar;
    ~Foo (void) {} // This Line
};
std::vector <Foo> foos;
foos.push_back (Foo ());

Here is what I think I understand about the situation:

It fails because unique_ptrs cannot be copied, and std::vector::push_back (thing) calls the thing's copy constructor. If I write Foo a custom copy constructor which explicitly moves bar, then everything will be fine.

However, disabling This Line will cause the code to compile.

I thought that this should fail to compile even without This Line, because I'm still attempting to push_back a unique_ptr.

Why does this succeed without the custom destructor, and why does adding the custom destructor cause it to fail?

Edit: using gcc -std=gnu++11 on Debian Linux 64-bit

like image 362
evenex_code Avatar asked Dec 15 '22 01:12

evenex_code


1 Answers

I can't guarantee this is what is happening in your case, but it is related to something I've seen lately:

You can't copy unique pointers, but you can move them.

In C++11 you will get a default move constructor if you don't define a destructor, but if you define one the compiler doesn't have to provide the move constructor, in which case the code fails. (I know that Visual Studio won't do this, but on my Mac with Xcode I've still gotten the move constructor.)

So, I think this is what is happening in your case. Try provide the destructor and the other constructors/assignment operators to see if it fixes things. (See the discussions on the rule of five.)

like image 98
Nathan S. Avatar answered May 22 '23 04:05

Nathan S.