C++日积月累—返回值优化

返回值优化(Return value optimization,缩写为RVO)是C++的一项编译优化技术。

#include 

struct CDemo
{
public:
    CDemo(int n) : p_var(new int(n))
    {
        std::cout << "constructor" << std::endl;
    }

    CDemo(const CDemo& other): p_var(new int(*other.p_var))
    {
        std::cout << "copy constructor function" << std::endl;
    }
    ~CDemo()
    {
        if (p_var != nullptr)
            delete p_var;
            p_var = nullptr;
    }
private:
    int* p_var;
};

CDemo create()
{
    return CDemo(1);
}

int main()
{
    std::cout << "begin" << std::endl;
    CDemo obj = create();
}

结果:
linux:


image.png

观察代码和运行结果,g++在加优化比没有加优化少运行了两次拷贝构造(同样也少运行两次析构函数)。
C++98/03低性能问题的之一,就是在以传值方式传递对象时隐式发生的耗时且不必要的深度拷贝。编译器对这个过程进行了优化,且不会影响程序的正确性,因此我们几乎不会去关注。

你可能感兴趣的:(C++日积月累—返回值优化)