shared_ptr
How to initialize a smart pointer shared_ptr
Because the pointer pointer uses the explicit parameter, the declaration initialization must be displayed
Shared_ptr<string> Pnico = new String ("Nico"); ERROR
Shared_ptr<string> pnico{new string ("Nico")}; Ok
You can also use make_shared ()
shared_ptr<string> Pnico = make_shared<string> ("Nico");
shared_ptr<string> Pjutta = make_shared<string> ("Jutta");
Once the smart pointer is declared
cannot be assigned again unless reset () is used
Shared_ptr<string> PNico4;
PNico4 = new String ("Nico");
Error:no assignment for ordinary pointers
Pnico4.reset (New String ("Nico")); Ok
SHARED_PTR is used in a similar way to the actual pointer use.
Example SharedPtrTest1 ()
//=======================================
for parameters in shared_ptr you can specify a deleter
Example SharedPtrTest2 ()
#include <iostream> #include <string> #include <vector> #include <memory> #include <fstream >//for ofstream#include <cstdio>//for remove () using namespace Std;void sharedPtrTest1 () {shared_ptr< String> Pnico (New string ("Nico"));shared_ptr<string> Pjutta (New string ("Jutta"));(*pnico) [0] = ' N ';p jutta- >replace (0, 1, "J");vector<shared_ptr<string>> Whomadecoffee;whomadecoffee.push_back (PJutta); Whomadecoffee.push_back (Pjutta); Whomadecoffee.push_back (Pnico); Whomadecoffee.push_back (PJutta); Whomadecoffee.push_back (Pnico); for (auto Ptr:whomadecoffee) {cout << *ptr << "";} cout << endl;//Overwrite a name Again*pnico = "Nicolai";//Print all elements againfor (auto Ptr:whomadecoffee) { cout << *ptr << "";} cout << endl;//Print some internal datacout << "Use_count:" << whomadecoffee[0].use_count () << E NDL;} Class filedeleter{private:std::string Filename;public:filedeleter (const std::string& fn): filename (fn) {}void operator () (std::ofstream* fp) {fp->close ();//close.filestd::remove ( Filename.c_str ()); Delete filecout << "Delete file Finish" << Endl;}; void SharedPtrTest2 () {shared_ptr<std::ofstream> FP (New Std::ofstream ("Tmpfile.txt"), Filedeleter (" Tmpfile.txt "));} int _tmain (int argc, _tchar* argv[]) {sharedPtrTest1 (); SharedPtrTest2 (); return 0;}
C++11 STL Learning shared_ptr