When should I use a shared pointer?

When should I use a shared pointer?

Use shared_ptr or intrusive_ptr when you want shared ownership of the pointer….The following is a good rule of thumb:

  1. When there is no transfer of or shared ownership references or plain pointers are good enough.
  2. When there is transfer of ownership but no shared ownership then std::unique_ptr<> is a good choice.

What is a raw pointer in C?

A raw pointer is a pointer whose lifetime is not 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.

Why are raw pointers bad?

Smart pointers typically keep track of the objects they point to for the purpose of memory management. The misuse of pointers is a major source of bugs: the constant allocation, deallocation and referencing that must be performed by a program written using pointers introduces the risk that memory leaks will occur.

How do I make a shared pointer thread safe?

  1. Correct, shared_ptr s use atomic increments/decrements of a reference count value.
  2. The standard guarantees only one thread will call the delete operator on a shared object.

Which is better shared pointer or raw pointer?

Dereferencing a shared pointer has the same performance as a raw pointer (depending on the compiler). A shared pointer needs two raw pointers. A set of shared pointers which have the same managed object need a control unit. Therefore, the memory that a shared pointer takes is more than a raw pointer and a unique pointer.

What is a shared pointer and how is it used?

The shared pointer is, in fact, a class which has a raw pointer pointing to the managed object. This pointer is called stored pointer. We can access it Use the stored pointer for accessing and working with the managed object not for modifying its ownership.

When to use raw pointers in C + +?

Use raw pointers when you do not want to have any ownership attached to the pointer. This job can also often be done with references. Raw pointers can also be used in some low level code (such as for implementing smart pointers, or implementing containers).

Is it safe to pass pointer to shared ptr?

It just has to access the pointer within the lifetime of the caller’s shared_ptr. In this case, it’s safe to pass the shared_ptr by reference, or pass the raw pointer or a reference to the underlying object. Passing this way provides a small performance benefit, and may also help you express your programming intent.