c++ - 为什么不调用移动构造函数?

标签 c++ c++11

为什么在此示例中没有打印任何内容?我在 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/

相关文章:

c++ - 在什么情况下我应该明确需要实现 move 构造函数和 move 赋值运算符?

C++、段错误和内存管理

c++ - 向右和向下重复输出 x 次

c++ - 使用 char16_t 类型作为 char[] 的数组,并通过 reinterpret_cast<> 重新转换它。我的代码是否有未定义的行为?

c++ - 图上的聚类(使用 Boost Graph Library)

c++ - 与可变参数模板相结合的成员指针数组的定义

c++ - 使用C++ RTTI(内省(introspection))通过字符串查找函数指针?

c++ - 将#include 指令包装到宏中

c++ - 使用 std::mutex 关闭头文件的 clr 选项

c++ - 重载运算符<<