How to create a pointer after creating shared_ptr?

std::shared_ptr<Investment> createInvestment() { std::shared_ptr<Investment> retVal(static_cast<Investment*>(0), getRidOfInvestment); // как тут передать в retVal указатель. return retVal; } 
  • tr1 not needed, instead of static_cast<Investment*>(0) you can write nullptr - VTT
  • one
    The book was written back then when shared_ptr was only in a project in tr1 . Perhaps then everything was somewhat different. - AnT

2 answers 2

You have a strange function, but if you really need it, you can use the reset function:

 retVal.reset(newInvestment, getRidOfInvestment); 
  • Why then did Maers pass a pointer to the cleaner's function when creating an empty smart point? - Stanislav Petrov

You can create a smart pointer shared_ptr two ways:
1) call the shared_ptr constructor, passing a pointer to the finished, already constructed object that it controls

 std::shared_ptr<Investment> retVal(new Investment()); 

2) use the special method make_shared , which creates an object of type T and returns the "smart" pointer of this class.

 std::shared_ptr<Investment> retVal = std::make_shared<Investment>(); 
  • I don’t understand why Maers in his book “Effective use of C ++. 55 right ways to improve the structure and code of your programs” in rule 18 drew such a construction. - Stanislav Petrov
  • one
    Maybe I have an old edition, but I don’t have such code in Chapter 18. What is the rule called? - Alexcei Shmakov
  • Rule 18: Design the interfaces so that it was easy to use them correctly and difficult - wrong - Stanislav Petrov
  • one
    in fact, this chapter describes that a smart pointer can bind its function, which deals with the removal of an object. But there is also a recommendation. Of course, if the pointer that pInv should control could be determined before creating pInv, then it would be better to transfer it to the pInv constructor instead of initializing pInv to zero and then assigning a value . And in order to bind an object to a smart pointer, you can either create a new smart pointer object and assign it to an existing dummy. Or call the reset method, pass a pointer to the constructed object. - Alexcei Shmakov
  • one
    @StanislavPetrov, this code really looks stupid, but you consider the chapter in which it is described. He there directly says that this chapter is not on shared_ptr , but on interfaces. True, it still does not justify such a code, he could use a better example. - ixSci