samedi 19 mars 2022

Does shared_ptr a = make_shared() create a copy of the shared_ptr before constructor is run?

This might be a stupid question.

Let's say we're in C++11 land and we use make_shared() to create a smart pointer. We then use this smart pointer to initialize a variable with like this:

std::shared_ptr<class> = make_shared(/* args to c'tor of class*/ );

Now I know two things:

  1. Assignement is not initialization. In this case we have initialisation. This would mean in the above case probably the copy constructor is called for the shared_ptr which is returned by make_shared.
  2. Copy elision is only mandatory in C++17.

Does this mean that on every instance of make_shared a temporary copy of the shared_ptr is created and inserted into the copy constructor? Because this would mean for thread safety that a lock would have to be taken across the initialisation in case other threads preempt the thread and call shared_ptr::use_count() member function?

Aucun commentaire:

Enregistrer un commentaire