从函数返回期间未调用复制构造函数

copy constructor not called during return from a function

本文关键字:调用 复制 构造函数 函数 返回      更新时间:2023-10-16

为什么在主函数的最后一行中没有为函数 func 的返回调用调用调用复制构造函数。当我按值发送参数时调用它,但在返回值时不调用它

class A
    {
        public:
        int x , y , z;
        A(int x=4 , int y=2 , int z=1)
        {
            this->x = x;
            this->y = y;
            this->z = z;
        }
        A(A& a)
        {
            x = a.x;
            y = a.y;
            z = a.z;
            printf("Copy Constructor calledn");
            a.x++;
        }
        //not a copy constructor
        A(A *a)
        {
            x = a->x;
            y = a->y;
            z = a->z;
            printf("Some Constructor calledn");
            (a->x)++;
        }
        void tell() { printf("x=%d y=%d z=%dn" , x , y , z);}
    };
    A func()
    {
    A a;
    return a;
    }
    int main()
    {
        A a1;
        a1=func(); //why is copy constructor not called while returning
        a1.tell();
        return 0;
    }

这是因为复制省略。允许编译器省略副本并将结果直接存储在对象中。您可以使用编译器选项-fno-elide-constructors 关闭复制 elision(不过我不建议这样做)。

相关:什么是复制省略和返回值优化?