我应该何时从操作员函数返回指向对象(而不是对象)的指针? [英] When should I return pointer to object (not an object) from the operator function?

查看:180
本文介绍了我应该何时从操作员函数返回指向对象(而不是对象)的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是的后续问题。我理解,它返回指针对象可以导致内存泄漏,也是因为原始指针他们容易出错,也棘手。所以,人数建议我不返回指针从操作员功能的对象。所以,我相信从操作员函数返回对象。但是我很好奇,知道有什么情况存在的时候,从重载的操作符函数返回指针到一个对象是罚款&

This is a follow up question to this. I understood that it returning pointer to object can result memory leak, also because of raw pointers they are error prone, also tricky. So,number of peoples advised me to not return pointer to an object from operator function. So,I am convinced to return object from operator function. But I am curious to know that are there any circumstances exist when returning pointer to an object from overloaded operator function is fine & desirable?

如果您的答案是肯定的,请使用合适的例子证明答案。

If your answer is yes, please justify the answer using suitable example.

请帮助我。

您的帮助将非常感激。

推荐答案

坏例子。简短答案:从(!)返回二进制函数(运算符)的指针。返回值或std :: unique_ptr或std :: shared_ptr。

You got a bad example. Short answer: never(!) return a pointer from a binary function (operator). Return by value or a std::unique_ptr or std::shared_ptr.

注意:问题链接中接受的答案随后改变。

Note: The accepted answer in the link of the question changed afterward.

这篇关于我应该何时从操作员函数返回指向对象(而不是对象)的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆