即使使用 -fno-elide-constructors 进行编译,似乎也会发生复制省略

Copy elision seems to occur even if compiling with -fno-elide-constructors

#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 的签名更改为

void f(A a)