ROV/NROV优化的作用

本篇博客以《深度探索C++对象模型》中例子来总结这两种优化技术。代码片段如下:

class Point3d
{
public:
    int m_x;
    int m_y;
    int m_z;
public:
    Point3d(int x,int y,int z):m_x(x),m_y(y),m_z(z)
    {
        cout << "constructor"<<endl;
    }
    ~Point3d()
    {
        cout << "deconstructor"<<endl;
    }
    Point3d(const Ponint3d &other)
    {
        this.m_x = other.m_x;
        this.m_y = other.m_y;
        this.m_z = other.m_z;
        cout << "copy constructor"<<endl;
    }
    Point3d &operator=(const Point3d &other)
    {
        if(this != &other)
        {
            this.m_x = other.m_x;
            this.m_y = other.m_y;
            this.m_z = other.m_z;
        }
        cout << "operator="<<endl;
        return *this;
    }
}
 
Point3d factory()
{
    Point3d po(1,2,3)
    return po;
}
 
int main()
{
    Point3d p = factory();
    return 1;
}

代码中显式定义了构造函数、拷贝构造函数、析构函数以及重载了赋值运算符,并在内部加入了一些打印信息来查看这些函数的调用情况。

1.当不做任何优化

运行后日志如下:

constructor      //factory函数中构造po对象
copy constructor //factory函数中用po对象拷贝构造临时对象_temp
deconstructor    //factory函数中返回时,析构掉局部对象po
copy constructor //main函数中用factory函数中拷贝构造的临时对象拷贝构造对象p
deconstructor    //析构临时对象_temp
deconstructor    //main函数结束时,析构对象p

这时候调用了三次构造函数

2.当使用RVO优化

factor函数改写为以下伪代码形式:

void factory(Point3d &_result)
{
    Point3d po;
    po.Point3d::Point3d(1,2,3);
    _result.Point3d::Point3d(po);   //用po拷贝构造_result;
    po.Point3d::~Point3d();         //po对象析构
    return;
}

返回值变为空,减少了临时对象的创建,减少一次构造函数调用。

对应的main函数中的赋值语句改写为

int main()
{
    Point3d p;
    factory(p);
    return 0;
}

对应输出如下:

constructor      
copy constructor 
deconstructor         
deconstructor       //main函数中p的析构

3.当使用NROV优化

factor函数改写为以下伪代码形式:

void factor(Point3d &_result)
{
    _result.Point3d::Point3d(1,2,3); 
    return;
}

同样返回值是空,直接将要初始化的对象替代掉局部对象进行操作,减少两次构造函数调用。

对应输出如下:

constructor  
deconstructor  main函数中析构函数

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值