开发者

question about smart pointers

开发者 https://www.devze.com 2023-01-03 16:02 出处:网络
I have this snippet of the code and I must write appropriate code withclass A (constructor, destructor, copy constructor, operator =), my question is do I need write smart pointers if I want that this

I have this snippet of the code and I must write appropriate code with class A (constructor, destructor, copy constructor, operator =), my question is do I need write smart pointers if I want that this code will work perfectly, if no, can you explain where writing smart pointers will be usef开发者_Python百科ul, thanks in advance

A *pa1 = new A(a2);
A const * pa2 = pa1;
A const * const pa3 = pa2;


Smart pointer are most useful when it is difficult to predict when an object should be deleted. For example: if you create an object in one point, and the object might be delete in another very distant point, or more importantly, might be deleted by several different places, smart pointers is the best solution. So basically, unless you can say for sure when an object should be deleted, and it will always be safe to do so (i.e. no other object holds a pointer to that object) use smart pointers.

Another point of view, which some friends use, is that smart pointers are so cheap (i.e. the processing cost of using them is very small), smart pointer should always be used when objects are allocated on the heap (i.e. using new). That way, you'll never have to worry about memory leakage or double-frees, etc.


A smart pointer is not needed, as non of the operations following new can throw. You just need:

A *pa1 = new A(a2);
A const * pa2 = pa1;
A const * const pa3 = pa2;
delete pa1;

If this isn't what you are asking about, please clarify your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号