General
Prefer unique_ptr by default. If you do know from the start you need shared ownership, however, go directly to shared_ptr via make_shared.
With unique_ptr , you can still put it in a container (e.g., vector<unique_ptr<widget>>) and do most other things you want to do with a raw pointer, only safely.
Whenever possible, use the make_shared function to create a shared_ptr when the memory resource is created for the first time.
For general use, take T*
or T&
arguments rather than smart pointers
Smart pointer rule summary
Unique pointer as class member
class A {
private:
std::unique_ptr<MyType> mt;
public:
void initStuff() {
mt = StaticFuncSomewhereElese::generateMyType();
}
};
std::unique_ptr<MyType> StaticFuncSomewhereElese::generateMyType() {
auto temp = std::make_unique<MyType>(…);
// `make_unique` is C++14 (although trivially implementable in C++11).
// Here's an alternative without `make_unique`:
// std::unique_ptr<MyType> temp(new MyType(…));
//do stuff to temp (read file or something...)
return temp;
}
Unique pointer in containers
std::unique_ptr<test1> us(new test1());
std::vector<std::unique_ptr<test1>> vec;
vec.push_back(move(us));
// or
vec.push_back(std::unique_ptr<test1>(new test1()));
// or
vec.push_back(std::make_unique<test1>()); // make_unique requires C++1
// FAIL: for (auto i: AVLTree) { ... } - tries to make a copy of each element.
for (auto& i: AVLTree) { ... }
for (auto const& i: AVLTree) { ... }
Links
- [1] https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/
- [2] https://learn.microsoft.com/en-us/cpp/cpp/how-to-create-and-use-shared-ptr-instances?view=msvc-170
- [3] https://github.com/isocpp/CppCoreGuidelines/blob/c553535fb8dda2839d13ab5f807ffbc66b63d67b/CppCoreGuidelines.md#c150-use-make_unique-to-construct-objects-owned-by-unique_ptrs
- [4] https://stackoverflow.com/questions/68669838/trouble-using-stdmake-unique-with-member-variable-of-class
- [5]
- https://stackoverflow.com/questions/42595473/correct-usage-of-unique-ptr-in-class-member
- [6] https://stackoverflow.com/questions/29972563/how-to-construct-a-vector-with-unique-pointers
- [7] https://stackoverflow.com/questions/20292682/iterating-through-vectorunique-ptrmytype-using-c11-for-loops