我的问题涉及如何返回没有复制构造函数的对象.举一个例子,让我们想象一下,我有一些bigResource位于堆中,让我们说我用它来跟踪它unique_ptr.现在假设我将此资源的所有权交给了毛毛虫.然后我有一个CaterpillarWithBigResource.现在在某些时候,这CaterpillarWithBigResource将变成一个ButterflyWithBigResource,所以Caterpillar对象必须将所有权转移到Butterfly对象.
我编写了以下代码来模拟情况:
#include <cstdlib>
#include <iostream>
#include <memory>
class ButterflyWithBigResource {
public:
// If I uncomment just this line, I get an error
// ButterflyWithBigResource(const ButterflyWithBigResource& other) = default;
// If I uncomment just this line, I get an error
// ButterflyWithBigResource(const ButterflyWithBigResource& other) = delete;
// With both above lines commented out, I get no errors, and the program runs fine.
ButterflyWithBigResource(std::unique_ptr<int>&& bigResource) :
bigResource(std::move(bigResource)) …Run Code Online (Sandbox Code Playgroud)