【发布时间】:2020-05-30 04:21:30
【问题描述】:
作为主题,相关代码为:
#include <iostream>
class ABC
{ public:
ABC()
{
std::cout<< "default construction" << std::endl;
}
ABC(const ABC& a)
{
std::cout << "copy construction" << std::endl;
}
ABC(const ABC&& a)
{
std::cout << "move construction" << std::endl;
}
};
int main()
{
ABC c1 = ABC();
return 0;
}
使用 -fno-elide-constructors -std=c++11 输出
default construction
move construction
如果我删除上面的移动构造函数,那么输出是:
default construction
copy construction
为什么 copy construction 可以在 move constructor 被删除时使用?你看,如果有用户定义的 move constructor,编译器更喜欢使用 move constructor。
根据一些文档,编译器提供了默认的move constructor。**那么为什么编译器不使用默认的move constructor?
我是 C++ 的新手。如果能在这个问题上得到一些帮助,我将不胜感激。
【问题讨论】:
-
ABC(const ABC&&)不是移动 ctor。删除 const:ABC(ABC&&). -
@谢谢。你能详细解释一下吗?我有点困惑,因为这段代码(删除关键字
const)[godbolt.org/z/YAwdMo]确实可以编译。 -
看来我错了。 Cppreference 说
T(const T&&)确实 算作移动 ctor。反正。从阅读 cppreference: rule of five 开始,然后点击链接到专门的 ctor/assignment 页面。 -
@besc 你认为
T(T&&)(没有关键字const)算作移动ctor吗?
标签: c++ c++11 constructor copy-constructor move-semantics