复制构造函数-理解问题 我在理解C++复制构造函数方面有一些问题,希望有人能帮助我。

复制构造函数-理解问题 我在理解C++复制构造函数方面有一些问题,希望有人能帮助我。,c++,copy-constructor,C++,Copy Constructor,据我所知,当一个函数返回一个类的实例时,就会调用复制构造函数 #include <iostream> using namespace std; class Test { int a; public: Test(int a) : a(42) {} // Copy constructor Test(const Test& other) { cout << "copy constructor" &l

据我所知,当一个函数返回一个类的实例时,就会调用复制构造函数

#include <iostream>
using namespace std;

class Test
{
    int a;
public:
    Test(int a) : a(42) 
    {}

    // Copy constructor
    Test(const Test& other) 
    {
        cout << "copy constructor" << endl;
    }
};

Test test_function()
{
    Test a(3);
    return a;
}

int main()
{
    test_function();
    return 0;
}

复制构造函数既不被调用,为什么不呢

提前谢谢

编辑: 将功能更改为:

Test test_function()
{
    Test a(3);
    Test b(34);

    if (4 < 2)
        return a;

    else
        return b;
}
Test\u函数()
{
试验a(3);
试验b(34);
如果(4<2)
返回a;
其他的
返回b;
}
可以看到复制构造函数调用,因为编译器不能使用RVO

Test test_function()
{
    Test a(3);
    return a;
}
此函数用于声明测试的本地副本并将其返回。编译器将看到,当它创建一个新副本时,意识到它即将销毁本地副本,并简单地将本地副本省略到结果中。要查看您想要的结果,这可能会更好:

Test test_function(const Test& t)
{
    return t;
}

int main()
{
    Test t1;
    Test t2 = test_function(t1);
    return 0;
}
它将(复制/移动)构造函数省略作为一种优化,以避免不必要的复制/移动。另一个可以应用的优化是完全忽略返回的任何内容,因为您根本不使用返回的值

无论如何,您可以禁用此优化,并通过此编译器开关(gcc)查看所需的消息:


但是,仅在测试中使用上述开关,并让优化应用于实际程序。

这是一种称为“命名返回值优化”(简称NRVO)的优化。在本例中,只有一个测试对象,要查看copyconstructors的运行,您至少需要两个对象。与Test b=Test_function()类似,编译器正确地观察到您没有使用返回值(这两种情况都没有),并且它优化了副本。复制省略是唯一允许改变程序可观察行为的优化。@jrok我猜它更有可能是NRVO。可能重复的
Test test_function()
{
    Test a(3);
    return a;
}
Test test_function(const Test& t)
{
    return t;
}

int main()
{
    Test t1;
    Test t2 = test_function(t1);
    return 0;
}
-fno-elide-constructors