Smart pointer vs owning raw pointer

1.9k views Asked by At

As far as I know, it's preferred to use a smart pointer instead of managing the lifetime of a dynamically allocated object through a raw pointer, e.g.: MyObject* obj = new Object();

But in some frameworks/libraries they always return/work with raw pointers instead of smart pointers, (maybe they have their own GC objects? I don't know).

It's also easier to work with

 MyObject* obj = GetAObject(); // return raw owning pointer

than

SharedPointer<MyObject> obj = GetAObject(); // return smart pointer

Should one always use smart pointers instead of manual new/delete (like in the example above) or are there any cases where raw resource-owning pointers should be used?

3

There are 3 answers

4
Baum mit Augen On

If your code is not required to compile with a pre-C++11 compiler, I see no reason to have owning raw pointers.

Even if your code needs to compile with ancient compilers, you should check out the smart pointers from Boost.

I do not know of a single situation in which an owning raw pointer would be a good idea.

Nothing wrong with non-owning raw pointers if appropriate.


It is true that a lot of code still uses owning raw pointers. This should fall mainly into two categories:

  1. Code older than Boost smart pointers/C++11
  2. Code written by people who do not follow modern C++ best practice.
0
sergico On

Working with smart pointer might saves you a lot of troubles chasing memory leaks. You can always wrap the pointers returned by a third party library into a smart pointer, but you need to be careful on who is really the owner of the allocated memory. You should read the library documentation to be sure that once you give the allocated memory to the smart pointer, someone else is not messing with it: for instance, as you suggested, if the framework has it's own garbage collector.

1
TartanLlama On

Pointer usage should be informed by the ownership semantics you are trying to model in your application.

If your library returns raw pointers to memory which the library manages, then raw pointers are absolutely fine. If it returns pointers to memory which your application should own, then smart pointers are a better choice, because you can forget about the memory management and your intent is documented by the code.