lego69
lego69

Reputation: 857

question about smart pointers

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 useful, thanks in advance

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

Upvotes: 2

Views: 171

Answers (2)

anon
anon

Reputation:

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.

Upvotes: 1

Gianni
Gianni

Reputation: 4390

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.

Upvotes: 2

Related Questions