Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Once you've adopted boost's smart pointers, is there any case where you use raw pointers?

I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"?

like image 324
ApplePieIsGood Avatar asked Dec 12 '08 16:12

ApplePieIsGood


People also ask

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.

When should you stop using smart pointers?

Since smart pointers are indicators about data ownership, I tend to avoid them when I don't own the data. Such a case occurs when referencing objects with ownership over the current scope (e.g. “parent” pointers). If a parent object owns the current scope and has a guaranteed existence, use a reference.

What are raw pointers?

A raw pointer is a pointer whose lifetime isn't controlled by an encapsulating object, such as a smart pointer. A raw pointer can be assigned the address of another non-pointer variable, or it can be assigned a value of nullptr . A pointer that hasn't been assigned a value contains random data.

Do you need to delete smart pointers?

So, we don't need to delete it as Smart Pointer does will handle it. A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.


1 Answers

I don't use shared_ptr almost at all, because I avoid shared ownership in general. Therefore, I use something like boost::scoped_ptr to "own" an object, but all other references to it will be raw pointers. Example:

boost::scoped_ptr<SomeType> my_object(new SomeType);
some_function(my_object.get());

But some_function will deal with a raw pointer:

void some_function(SomeType* some_obj)
{
  assert (some_obj);
  some_obj->whatever();
}
like image 163
Nemanja Trifunovic Avatar answered Nov 12 '22 06:11

Nemanja Trifunovic