This question already has answers here:
How does guaranteed copy elision work?

(1个答案)



Why isn't the copy-constructor called when returning LOCAL variable

(1个答案)


7个月前关闭。



#include <iostream>

class studant {
    public:
    studant () {
        std::cout<<"studant"<<std::endl;
    }
    studant(const  studant& a) {
        std::cout<<"copy studant (&)"<<std::endl;
    }
   studant(studant&& a) {
        std::cout<<"move studant (&)"<<std::endl;
    }
    studant maximum () {
        studant c1;
        return c1;
    }
};
studant create () {
     studant c1;
    return c1;
}
int main()
{
    studant c2;
    studant c3=c2.maximum ();
    studant c4=create ();
}

请参见上面的代码,为什么“studant c3 = c2.maximum()”和“studant c4 = create()”未调用复制或移动构造函数。请给我解释一下。

最佳答案

这是因为RVO(返回值优化)。 studant c3=c2.maximum ()调用maximum(),编译器知道c1中的maximum()将被返回,然后分配给c3,然后c1将被丢弃。编译器足够聪明,可以创建一个studant实例来避免分配。这意味着c1中的maximum()c3是相同的实例。

函数“create()”中的“c4”和c1相同。

关于c++ - 在C++中移动和复制构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61556571/

10-10 04:59