【发布时间】:2021-06-29 03:01:11
【问题描述】:
为什么调用移动构造函数而不是复制构造函数?当我删除移动构造函数时,就会调用复制构造函数。
使用:-fno-elide-constructors 避免复制省略
#include <iostream>
class test
{
public:
int x;
char y;
bool t;
test()
{
std::cout << " constructed" << std::endl;
}
test(test &&temp)
{
std::cout << "move constructor" << std::endl;
}
test(const test &temp)
{
std::cout << "copy constructor" << std::endl;
}
template <typename... Args>
static test create(Args... x)
{
test b(x...);
return b;
}
};
int main()
{
test z = test::create();
test v = test();
}
输出:
constructed
move constructor
move constructor
constructed
move constructor
上述情况可能是什么原因?
【问题讨论】:
-
为什么这让您感到惊讶?分配时会自动移动临时值
-
这很有趣。你用的是什么编译器?我本来希望复制省略可以工作,所以唯一的输出应该是“构造的”。
-
我试过了:godbolt.org/z/8EcbbTKf5 gcc 和 clang 只打印
constructed constructed,即使是几年前的版本。 -
您期望什么行为?您希望在哪里调用复制构造函数,为什么?对我来说,这里唯一有趣的是你的问题的标题不是“为什么使用移动构造函数而不是省略?”。
-
@MariusBancila 我明确使用了“-fno-elide-constructors”
标签: c++ move copy-constructor move-semantics copy-elision