Home > Software engineering >  Return a smart pointer dereference as a reference type
Return a smart pointer dereference as a reference type

Time:10-24

const string& show_string(){
    std::shared_ptr<std::string> p = std::make_shared<std::string>("test");
    return *p;
}

A novice question:Will this usage cause dangling reference?

CodePudding user response:

Yes

std::shared_ptr will delete the object it owns when the last std::shared_ptr sharing ownership of that object is destroyed. In this case, p is the only std::shared_ptr pointing to your string, and it is local to show_string, so that string will be destroyed as soon as show_string returns, leaving the returned reference dangling.

  •  Tags:  
  • c
  • Related