Article Directory
- 1 Several ways to initialize std::shared_ptr
- 1.1 Constructor initialization
- 1.2 std::make_shared initialization (recommended method)
- 1.3 reset initialization
1 Several ways to initialize std::shared_ptr
Here I will only summarize the several methods of std::shared_ptr initialization, and do not explain the advantages and disadvantages of std::shared_ptr. There are many ways to initialize, and I often get confused and memorable when typing.
1.1 Constructor initialization
std::shared_ptr<int> pointer(new int(1));
std::shared_ptr<int> pointer1 = pointer;
std::shared_ptr<std::string> ss(new std::string("AAA"));
std::shared_ptr<std::string> = std::shared_ptr<std::string>(new std::string("AAA"));
1.2 std::make_shared initialization (recommended method)
std::shared_ptr<string> p3 = std::make_shared<string>();
std::shared_ptr<string> p2 = std::make_shared<string>("hello");
//Instead of std::shared_ptr, p5 points to a dynamically allocated empty vector<string>
auto p5 = make_shared<vector<string>>();
1.3 reset initialization
std::shared_ptr<int> pointer = nullptr;
pointer.reset(new int(1));
If you are interested, you can visit my personal website: