C++对象加法重载时如何最大限度的减少内存开销

//常规中我们有很多办法以减少内存开销,但是每次对象的复制都是一次复制构造函数的执行
//效率和内存占用居高不下,经难度,本例或可作为一种思路
//只是本人首次尝试研究,初步构想,实践中是否可行还有待考证
//敬请广大网友批评指正
#include <iostream>

using namespace std;
class demo
{
public:
    demo();
    demo(int a);
    demo(const demo& tmp);
    ~demo();
    const demo& add(const demo & a, const demo& b);
    const demo * constoperator+(const demo & tmp);
    void set(int a);
    int get()const;
private:
    int x;
};

int main()
{
    demo fta(5),ftb(6);
    const demo * const fts =fta + ftb;
    cout<< "ADD:"<< fts->get()<< endl;
    return 0;
}

demo::demo()
{
    cout<< "Original constructorrunning...\t";
    cout<< x <<endl;
}

demo::demo(int a)
{
    x = a;
    cout<< "Set value constructorrunning...\n";
}

demo::demo(const demo & tmp)
{
    this->x =tmp.x;
    cout<< "Copy constructorrunning...\t";
    cout<< x <<endl;
}

demo::~demo()
{
    cout<< "Destructor running...\n";
}

const demo & demo::add(const demo& a, const demo & b)
{
    this->x =a.x + b.x;
    cout<< "Two objects...\n";
    return *this;
}
const demo * const demo::operator+(const demo& tmp)
{
    cout<< "Direct memory address accessmode, no objects will be copied.\n";
    this->x =this->x + tmp.x;
    return this;
}

void demo::set(int a)
{
    x = a;
}

int demo::get()const
{
    return x;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网速递520

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值