"Rui Maciel" wrote in message news:k4msvs$4g8$...
Mikewhy wrote:
> The question is, assuming that multithread issues are not present, how
> easily can naive code cause trouble for itself with a const reference
> return interface? What usage patterns (that have a chance of surviving the
> low threshold of a peer review) might prove problematic?
int main(void)
{
const int *bar = NULL;
{
Foo foo;
bar = &foo.getter();
std::cout << "accessing object at " << bar << ". value is: "
<< *bar << std::endl;
}
std::cout << "accessing object at " << bar << ". value is: " << *bar
<< std::endl;
return 0;
}
</code>
======================
That's basically the gist of it. One expects even the most cursory review to
catch something so blatant, even a few levels deep in function calls or
object ownership.
As a short sidebar, before moving on, in your example above, return by value
would also be equally noteworthy with some older compilers. Just how bad
depends on which compiler (some being already quite old and will continue to
be in widespread use for some long time to come). To wit:
const std::string & aval = alookup.get_val(); // return by value,
This is (purportedly?) reasonably safe in C++11, but at least one compiler I
know personally will allow it to fail at runtime with only an ignorable
warning at compile time.
It isn't the dunderheaded error exemplified by both of the above that I'm
after. I'm after reasonable looking usage that despite best efforts and
intentions of experienced and competent engineers still can fail. When we
talk of safety in this context, we are talking specifically about relative
lifetimes of the reference and referencee. Rather than a revelation, this is
already I expect an ingrained and abiding paranoia in everyone still reading
this. It is, after all, the basis and reason that shared_ptr and friends
exist.
I think I'll conclude here, maybe prematurely, that it is NOT return by
const ref that is unsound or unsafe. It is careless or inappropriate usage
or storage that can be problematic. Return by const ref rather than value
does not of itself make usage errors any more or less likely. If you don't
know or can't control the lifetime of the referenced, either through
ownership, explicit guarantee, or reference counts, storing a copy is a
reasonable alternative. I believe this to apply both in general and in this
particular discussion.
Your further thoughts, please....
|