为什么在此示例中没有打印任何内容?我在 Coliru 上用 Clang 编译。
#include <iostream>
struct S
{
S() noexcept = default;
S(S&&) noexcept { std::cout << "move-ctor"; }
};
void f(S) {}
int main()
{
f(S{});
}
最佳答案
编译器正在执行复制省略,这是 C++11 标准第 12.8/31 段所允许的,即使您的移动构造函数、复制构造函数或析构函数有副作用也是如此:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects.
即使在省略移动时也使用术语复制省略:
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
[...]
— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
[...]
使用 GCC,您可以使用 -fno-elide-constructors
来禁止复制省略。在这种情况下,您会看到移动构造函数被调用,如 live example 所示。 .
关于c++ - 为什么不调用移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872799/