问题描述
我的课不好听。复制此文件将有问题。我想保证永远不会被复制,所以我将其复制构造函数删除了
:
I have an uncopiable class. Copying this would be problematic. I want to guarantee that it won't be ever copied, so I made its copy constructor deleted
:
class A {
public:
A();
A(const A&) = delete;
};
A fun() {
return A();
};
int main() {
A a = fun();
};
不幸的是,g ++不会基于以下原因对其进行编译:
Unfortunately, g++ won't compile this on the reason:
t.cc: In function ‘A fun()’:
t.cc:8:12: error: use of deleted function ‘A::A(const A&)’
return A();
^
t.cc:4:5: note: declared here
A(const A&) = delete;
^
t.cc: In function ‘int main()’:
t.cc:12:13: error: use of deleted function ‘A::A(const A&)’
A a = fun();
^
t.cc:4:5: note: declared here
A(const A&) = delete;
^
但这是一个非常明显的情况,应使用复制省略,因此复制构造函数永远都不会被调用。为什么会这样呢?
But this is a very clear situation where copy elision should be used, so the copy constructor shouldn't be ever called. Why is it so?
推荐答案
直到C ++ 17复制省略是编译器不需要进行的优化,所以类必须是可复制的,因为编译器可能要复制(即使实际上不希望复制)。在C ++ 17中,在许多情况下都可以保证复制省略,然后类将不需要复制ctor。
Until C++17 copy elision is an optimization the compiler is not required to do, so classes must be copyable since the compiler might want to copy (even if it actually does not). In C++17 copy elision will be guaranteed in many cases and then classes won't need copy ctors.
另请参见:
(关于保证复制省略的意思)
https://herbsutter.com/2016/06/30/trip-report-summer-iso-c-standards-meeting-oulu/(the bit about "Guaranteed copy elision")
您也许可以使用宣告复制构造函数的旧技巧在您的课程中,但实际上并未实现吗?只要编译器实际上不调用复制ctor,就应该满意。我没有测试过,但是我相信它应该在您的情况下有效,直到C ++ 17到来。
You could perhaps use the old trick of declaring the copy constructor in your class but not actually implement it? That should please the compiler as long as it does not actually invoke the copy ctor. I didn't test that, but I believe it should work for your case until C++17 arrives.
这篇关于如何执行复制省略,为什么它不适用于删除的复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!