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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With