mardi 6 août 2019

Receving a variable as a refernece in c++ with shared_ptr

I just wondering if the following way of delivering a pointer variable, created inside of the func1, to the caller (func2) is a correct way of doing this. If this is correct, will it release the memory when func2 is returned? If it is a bad idea, why is that?

int & func1(){
  std::shared_ptr<int> d = std::make_shared<int>(50);
  return *d;
}


void func2(){
  
    int & dd = func1();   
    
}

This is a simplified code. I am assuming the size of d is huge(e.g images).

Added: I realized that the following also works. What will be the pros and cons of each approach?

std::shared_ptr<int> & func1(){
  std::shared_ptr<int> d = std::make_shared<int>(50);
  return d;
}
void func2(){  
    std::shared_ptr<int> & dd = func1();   
}

Aucun commentaire:

Enregistrer un commentaire