How to return dynamic object from operator function?

随声附和 提交于 2019-12-12 10:17:25

问题


I am quite confused about this. How to return a dynamically allocated object from operator function? Consider following example:

#include "stdafx.h"
#include <iostream>
#include "vld.h"
using std::cout;
class Point
{
    public:
    Point(int x,int y) : a(x),b(y)
    { }
    Point()
    { }
    Point operator + (Point p)
    {
        Point* temp=new Point();
        temp->a=a+p.a;
        temp->b=b+p.b;
        Point p1(*temp);  // construct p1 from temp
        delete temp;      // deallocate temp
        return p1;
    }
    void show()
    {
        cout<<a<<' '<<b<<'\n';
    }
    private:
        int a,b;
};
int main()
{
    Point* p1=new Point(3,6);
    Point* p2=new Point(3,6);
    Point* p3=new Point();
    *p3=*p2+*p1;
    p3->show();
    VLDEnable();
    delete p1;
    delete p2;
    delete p3;
    VLDReportLeaks();
    system("pause");
}

Can I write this program without extra object p1 in this case in overloaded operator + function? How Can I directly return temp?

Your help will be highly appreciated.

Please help me.


回答1:


You are a bit confused between Java syntax and C++. In C++, there is no need for new unless you want your objects to be dynamically allocated (on the heap). Just use

Point temp; // define the variable
// process it
return temp;

In this way, your local objects will be created on the stack, and you won't have to care about forgetting to delete them etc.

Returning a pointer from operator+ is wrong

Point* operator + (Point p) 
{ 
    Point* tmp = new Point;
    // process
    return tmp; // return the pointer to the dynamically-allocated object
}

It actually breaks the operator+, since you won't be able to chain it, i.e. a+b+c won't work anymore. That's because a + b returns a pointer, then a + b + c tries invoking operator+ on a pointer, for which is not defined. Also, there are more serious issues, like leaking memory during the construction of your temporary objects in assignments, see @Barry's comment below. So I hope I have convinced you to return the object and not a pointer to it.



来源:https://stackoverflow.com/questions/30166644/how-to-return-dynamic-object-from-operator-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!