Preferred way to create shared pointers

The documentation states that it std::make_shared<T>usually allocates memory for Tand the smart pointer control unit at the same time as opposed to std::shared_pointer<T>(new T)that which performs two allocations. Does this mean that it is more effective and should therefore always be used std::make_sharedif possible?

The same question about the equivalent of Qt - QSharedPointer. According to the docs, the internal elements QSharedPointerand the object are distributed in the same memory allocation, which can help reduce memory fragmentation in the long term expression. Does this mean which QSharedPointer<T>::create()is preferable?

class MyClass {};

QSharedPointer<MyClass> ptr1 = QSharedPointer<MyClass>::create();   // better
QSharedPointer<MyClass> ptr2(new MyClass);  // worse
+4
source share
1 answer

std::make_sharedis preferred in almost every case. However, if you use weak pointers, you can easily get into a “memory leak” situation, where the memory is stored for much longer than you think at first glance (after all, shared_ptrgone).

As long as there is std::weak_ptrone associated with the control unit std::shared_ptr, the control unit must remain. Since it std::make_sharedcreates a single memory allocation for both the control unit and the data, if the control unit remains, the data must also remain. C std::shared_ptrthere are two distributions, therefore they can be cleared independently.

, std::weak_ptr ( ), std::make_shared , . std::weak_ptr, .

++ 4 , . ++, ++ 11/14, .

edit: @midor, std::make_shared. , T , , () {}, (). std::make_shared<std::vector>(10,10) std::vector(10,10) std::vector{10,10}.

+10

Source: https://habr.com/ru/post/1656899/


All Articles