mardi 29 octobre 2019

Is it legal to return a deference of newly allocated shared_ptr in a function return?

Is this code ok? I know that the reference counter is getting down to zero after the function returns, so the memory should be freed. But it works and prints the dereference successfully outside the function.

Can someone please explain if what I am trying to do is wrong or not, and why? Thanks

#include <iostream>
#include <memory>
#include <string>

std::string& get_string(bool en)
{ 
  return *std::make_shared<std::string>("hello world");
}

int main () {
  auto& my_str = get_string(true);
  std::cout << "str=" << my_str <<std::endl;
  return 0;
}

output:

> ./main
str=hello world

Aucun commentaire:

Enregistrer un commentaire