Re: Best practice: return by value versus const ref
Rui Maciel wrote:
Returning references may cause some significant problems in some
circumstances, if you can't guarantee that the object will only be
accessed during its lifetime. If you can't guarantee that then it's quite
possible that you might end up trying to access an object which doesn't
really exist.
Here is another example which better demonstrates what I was referring to:
<code>
#include <iostream>
struct Foo
{
int some_object;
Foo(int some_value = 0);
~Foo();
int const &getter() const {return some_object; }
};
Foo::Foo(int some_value)
: some_object(some_value)
{
std::cout << "Object constructed" << std::endl;
}
Foo::~Foo()
{
std::cout << "Object destructed. He's dead, Jim." << std::endl;
}
struct Bar
{
float some_other_object;
Bar(float some_value = 5.0f);
~Bar();
float const &getter() const {return some_other_object; }
};
Bar::Bar(float some_value)
: some_other_object(some_value)
{
std::cout << "Bar object constructed" << std::endl;
}
Bar::~Bar()
{
std::cout << "Bar object destructed" << std::endl;
}
int main(void)
{
char buffer[10] = {0};
const int *value = NULL;
const float *other_value = NULL;
// object is created in a specific address
Foo *foo = new(buffer) Foo(1);
value = &foo->getter();
std::cout << "accessing foo's object at " << value << ". value is: "
<< *value << std::endl;
// foo's lifetime ends
foo->~Foo();
// a new object has been allocated on top of the old one
Bar *bar = new(buffer) Bar;
other_value = &bar->getter();
std::cout << "accessing foo's object at " << value << ". value is: "
<< *value << std::endl;
std::cout << "accessing bar's object at " << other_value << ". value
is: " << *other_value << std::endl;
bar->~Bar();
return 0;
}
</code>
Rui Maciel