我的问题涉及如何返回没有拷贝构造函数的对象。举个例子,我们假设我有一些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)) {
}
const int& getResource() {
return *bigResource;
}
private:
std::unique_ptr<int> bigResource;
};
class CaterpillarWithBigResource {
public:
CaterpillarWithBigResource(int bigResource) :
bigResource(new int(bigResource)) {
}
ButterflyWithBigResource toButterfly() && {
return ButterflyWithBigResource(std::move(bigResource));
}
private:
std::unique_ptr<int> bigResource;
};
/*
*
*/
int main(int argc, char** argv) {
CaterpillarWithBigResource caterpillarWithBigResource(5);
ButterflyWithBigResource butterflyWithBigResource(std::move(caterpillarWithBigResource).toButterfly());
std::cout << butterflyWithBigResource.getResource() << std::endl;
return 0;
}
注意,无论是Caterpillar
还是Butterfly
有默认的拷贝构造函数,因为他们每个人都有一个unique_ptr
。然而,我不希望这是问题,所以只有移动构造函数才是必要的。毕竟,我只是将所有权从Caterpillar
转移到Butterfly
。
事实上,当我使用g++
版本4.8.2
编译程序g++ -c -g -std=c++11 -MMD -MP -MF
它工作得很好。
但现在奇怪的是,如果我要提醒的是,Butterfly
的拷贝构造函数被删除编译器通过将线ButterflyWithBigResource(const ButterflyWithBigResource& other) = delete;
,程序不再编译,编译器抱怨的拷贝构造函数被删除,这样我可以在toButterfly
方法中不返回Butterfly
。
如果我然后试着告诉它,一切正常,而不是行ButterflyWithBigResource(const ButterflyWithBigResource& other) = default;
,我再次得到相同的错误。
我希望发生的是在toButterfly
方法构建的Butterfly
被转移到toButterfly
的返回地址,再后来用作Butterfly
的说法“在main()
构建butterflyWithBigResource
时的举动的构造。有没有办法做到这一点?
BTW,返回,没有拷贝构造一个对象,你会使用复印通list-initialization:'return {std :: move(bigRes我们)}' – 0x499602D2