What Myers wanted to say with the following code.

std::tr1::shared_ptr<Investment> createInvestment() { std::tr1::shared_ptr<Investment> retVal(static_cast<Investment*>(0), getRidOfInvestment); ... // make retVal point to the // correct object return retVal; } 

why in retVal 0 is passed, and how then before return return a pointer in retVal.

  • I guess what exactly might confuse here ... - Fat-Zer
  • What kind of book and who year of publication? - Cerbo
  • Judging by the fact that shared_ptr in tr1 assume that the book is old and nullptr was not in the standard then. In modern C ++, it’s enough to static_cast<Investment*>(0) to write nullptr . - Cerbo

2 answers 2

0 is transmitted, because the real object has not been created yet and if it could not be created, then shared_ptr pointing to the zero pointer will return. Assign for example like this:

 retVal = std::tr1::shared_ptr<Investment>(new InvestmentEx(), getRidOfInvestment); 
  • it is not clear why we first create a shared_ptr object passing it a null pointer - Stanislav Petrov
  • one
    Suppose you have this factory method, which in some situations may simply not create an object - memory or other conditions have ended, then you need to return a zero object. - Unick
  • if you need to return a shared_ptr containing a null object, then why during the construction of retVal is a pointer to the cleaner function passed. - Stanislav Petrov

This example shows the idea of ​​an automatic "cleanup". The createInvestment function creates an "investment" (entity). But you need to remember to close it (delete, end). While the user (programmer) stores the returned smart pointer, the investment object lives. When the pointer goes out of scope, the "completion" function will be automatically called.