【问题标题】:Copy elision seems to occur even if compiling with -fno-elide-constructors即使使用 -fno-elide-constructors 编译,似乎也会发生复制省略
【发布时间】:2016-11-25 08:45:50
【问题描述】:
#include <iostream>

class A {
public:
    A() { std::cout << "Constructor" << std::endl; }
    A(const A& a) { std::cout << "Copy Constructor" << std::endl; }
    A& operator=(const A& a) { std::cout << "Copy = operator" << std::endl; }
    A(A&& a) { std::cout << "Move Constructor" << std::endl; }
    A& operator=(A&& a) { std::cout << "Move = operator" << std::endl; }
    ~A() { std::cout << "Destructor" << std::endl; }
};

void f(A&& a) { std::cout << "function" << std::endl; }

int main() {
    f(A());
    return 0;
}

以下程序的输出是:

Constructor
function
Destructor

为什么这里没有调用移动构造函数?即使我使用标志 -fno-elide-constructors 编译,似乎也会发生复制省略:g++ test.cpp -fno-elide-constructors -std=c++11

【问题讨论】:

  • 我是不是特别笨?当然A() 调用默认构造函数,然后匿名临时可以绑定到f(A&amp;&amp;)。我错过了什么?只有当你有一个构造对象时才能调用移动构造函数。
  • @Bathsheba:我认为你没有遗漏任何东西。给定A foo();,然后A a{foo()}; 将调用移动构造函数,但事实上,没有什么可移动的。
  • @Bathsheba “我错过了什么?”我不知道... 一些优质的个人时间?也许也有一些睡眠? (别介意我,只是在开玩笑。友好的玩笑,没有恶意)。
  • 这不是问题,但不要使用std::endl,除非你需要它的额外功能; '\n' 结束一行。

标签: c++ c++11 move-semantics copy-elision


【解决方案1】:

简答:你没有在移动构建任何东西

您只是创建一个临时的Aobject,然后传递一个对它的引用。如果您想查看移动施工,您可以例如将f的签名改为

void f(A a)

【讨论】:

    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 2015-01-21
    • 2022-12-14
    • 2012-08-27
    • 2014-01-30
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多