My questions are about how to return an object that does not have a copy constructor. As an example, suppose I have a bigResource that sits on a heap and say that I track it with unique_ptr . Now suppose I transfer this resource to the caterpillar owner. Then I have CaterpillarWithBigResource . Now at some point this CaterpillarWithBigResource will turn into a ButterflyWithBigResource , so the Caterpillar object will have to transfer ownership of the Butterfly object.
I wrote the following code to simulate a situation:
#include <cstdlib>
Note that neither Caterpillar nor Butterfly have default copy constructors, as each one has unique_ptr . However, I would not expect this to be a problem, so you only need to move the constructors. In the end, I transfer ownership only from Caterpillar to Butterfly .
In fact, when I compile the program using g++ -c -g -std=c++11 -MMD -MP -MF using g++ version 4.8.2 , it works fine.
But now the strangest thing is if I remind the compiler that the Butterfly copy constructor is removed by adding the string ButterflyWithBigResource(const ButterflyWithBigResource& other) = delete; , the program no longer compiles, and the compiler complains that the copy constructor has been removed, so I cannot return Butterfly in the toButterfly method.
If I try to say that everything is fine, instead of the string ButterflyWithBigResource(const ButterflyWithBigResource& other) = default; I get the same error again.
I want the Butterfly built in the toButterfly method to be moved to the toButterfly return address, and then later used as an argument to the Butterfly move constructor when building ButterflyWithBigResource in main() . Is there any way to do this?
c ++ copy-constructor c ++ 11 move-semantics move-constructor
Brian moths
source share