Boost logo

Boost Users :

Subject: Re: [Boost-users] [Filesystem] V3 interface inconsistency
From: Nat Linden (nat_at_[hidden])
Date: 2011-02-25 22:27:27


On Thu, Feb 24, 2011 at 3:13 AM, Peter Klotz
<Peter.Klotz_at_[hidden]>wrote:

Wouldn't it make sense for all methods to return a value instead of a
> reference?
>
> It would ease the transition from V2 to V3 and avoid subtle programming
> errors.
>

This is a more general comment than just about Boost.Filesystem. I've pretty
much concluded that string methods, at least virtual methods, should always
return std::string rather than const std::string&.

An accessor that returns a const reference to a data member is little better
than direct read access to the data member. The reason we use accessors in
the first place is to permit us to later introduce additional logic if need
be: to return a computed value. But returning a reference forbids that.

I've been burned a few times by a base class with a virtual method returning
const std::string&. Of course the base-class implementation simply returns a
data member, and it remains fine as long as no subclass needs to override it
with real logic. But the first time you have to compute a return value in
some override method -- you have to change ALL the return types for that
method in the whole class hierarchy. Gack!

Pass by const reference, but return by value.



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net