为什么未调用move-constructor? [英] Why is the move-constructor not called?

查看:75
本文介绍了为什么未调用move-constructor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在此示例中什么都没有打印?我正在用Coliru的Clang进行编译。

Why is nothing being printed in this example? I'm compiling in Clang on Coliru.

#include <iostream>

struct S
{
    S()    noexcept = default;
    S(S&&) noexcept { std::cout << "move-ctor"; }
};

void f(S) {}

int main()
{
    f(S{});
}


推荐答案

编译器正在执行 copy Elision ,即使您的move构造函数,copy构造函数或destructor产生副作用,C ++ 11标准第12.8 / 31段也允许使用该命令:

The compiler is performing copy elision, which is allowed per paragraph 12.8/31 of the C++11 Standard even if your move constructor, copy constructor, or destructor have side effects:


满足特定条件时,即使选择了用于复制/移动操作的构造方法和/或,也允许实现省略
类的复制/移动构造。

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.

甚至使用了 copy elision 这个术语。当移动被取消时:

The term copy elision is used even when a move is being elided:


这种复制/移动操作的省略,称为复制删除 在以下情况下是允许的(
可以合并以消除多个副本):

This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

[...]

-当尚未绑定到引用的临时类对象时e(12.2)将
复制/移动到具有相同cv-unqualtype类型的类对象,
可以省略复制/移动操作,方法是将临时对象直接构造到省略副本的目标中/ move

— 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 禁止复制省略。在这种情况下,您会看到调用了move构造函数,如 strong>实时示例

With GCC, you can use the -fno-elide-constructors to inhibit copy elision. In this case, you would see that the move constructor gets invoked, as in this live example.

这篇关于为什么未调用move-constructor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆