Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Smart Pointers as a Programming Standard?

More and more I hear, that I should use smart pointers instead of naked pointers, despite I have effective memory leak system implemented.

What is the correct programming approach on using smart pointers please? Should they really be used, even if I check memory leaks on allocated memory blocks? Is it still up to me? If I do not use them, can this be considered as programming weakness?

If the smart pointers(ex: std::auto_ptr) are strongly recommended, should I use them instead of every naked pointer?

like image 602
Bunkai.Satori Avatar asked May 26 '11 16:05

Bunkai.Satori


People also ask

What is the use of smart pointers?

In modern C++ programming, the Standard Library includes smart pointers, which are used to help ensure that programs are free of memory and resource leaks and are exception-safe.

How many types of smart pointers are there in C++?

The three types of smart pointers, as of C++11, are listed as follows: std::unique_ptr. std::shared_ptr. std::weak_ptr.

What is an advantage of using a smart pointer over a raw pointer?

One of the advantages of smart pointers is, that they ensure due to RAII, that the actual object is deleted. When using a raw pointer, you need to have a delete for every possible exit point, and still an exception will lead to a memory leak. Smart pointers will also free the memory if an exception occurs.

What are the different types of smart pointers?

C++ libraries provide implementations of smart pointers in following types: auto_ptr.


1 Answers

You should use RAII to handle all resource allocations.

Smart pointers are just one common special case of that rule.

And smart pointers are more than just shared_ptr. There are different smart pointers with different ownership semantics. Use the one that suits your needs. (The main ones are scoped_ptr, shared_ptr, weak_ptr and auto_ptr/unique_ptr (prefer the latter where available). Depending on your compiler, they may be available in the standard library, as part of TR1, or not at all, in which case you can get them through the Boost libraries.

And yes, you should absolutely use these. It costs you nothing (if done correctly, you lose zero performance), and it gains you a lot (memory and other resources are automatically freed, and you don't have to remember to handle it manually, and your code using the resource gets shorter and more concise)

Note that not every pointer usage represents some kind of resource ownership, and so not all raw pointer usage is wrong. If you simply need to point to an object owned by someone else, a raw pointer is perfectly suitable. But if you own the object, then you should take proper ownership of it, either by giving the class itself RAII semantics, or by wrapping it in a smart pointer.

like image 184
jalf Avatar answered Oct 18 '22 01:10

jalf