I am reasoning about the best approach to return references to objects created inside a method, like in the following situation:
class A{
public:
A(){}
~A(){}
};
class Foo{
public:
Foo(){}
~Foo(){}
A& create(int random_arg){
// create object A and return its reference
}
};
void other_method(){
Foo f;
A a = f.create();
// do stuff with a
{
I have considered three possible solutions:
create a raw pointer and return a reference, but this is bad because there is no guarantee that the object will be properly deleted:
A& create(int random_arg){ A* a = new A(); return *a; }
create a shared_ptr and return the shared_ptr by value. In this way the shared_ptr will take care of the object deletion:
shared_ptr<A> create(int random_arg){ boost::shared_ptr<A> a_ptr(new A()); return a_ptr; }
create a shared_ptr and return a reference:
A& create(int random_arg){ boost::shared_ptr<A> a_ptr(new A()); return *a_ptr; }
The second solution seems to be the most used, but in this way I have to spread shared_ptr in the application and I would prefer to have references, or better const
references.
What do you think is the best way to handle this situation? Are there other possibilities I have not considered?
A a; return a;
. Follow the KISS principle. – TikiA& create() { A a; return a; }
which has the same problem as (3) – Tiki