Boost logo

Boost Users :

Subject: Re: [Boost-users] [Any] inconsistent return types of any_cast overloads
From: Nat Goodspeed (nat_at_[hidden])
Date: 2013-12-04 09:29:36


On Wed, Dec 4, 2013 at 7:07 AM, Krzysztof Czainski <1czajnik_at_[hidden]>wrote:

I think taking values returned by value by const & to extend their lifetime
> should be deprecated in new C++ - compilers could then warn not to do it.
>

I like that idea!

One C++03 usage that has bothered me for a long time is a base class which
stores one or more std::string data members, with virtual methods that
return const std::string&. In an override method on one existing subclass,
I decide to compute a std::string return value. But I can't return a
temporary, and I can't return a stack variable! I have two bad choices: I
can add a new private std::string data member to the subclass specifically
to store the return value from this method; or I can refactor every
declaration of this method in the entire class hierarchy to return by value.

(We will loftily ignore the even worse choice of storing a module-static
std::string for the method return value.)

I have several times decided to refactor the method signature throughout
the class hierarchy. But by the time I'm doing that much work, I typically
also change the signature of every virtual method returning const
std::string& to return by value -- to spare myself, or someone else, the
pain of having to do it later.

I've pretty much concluded that a virtual method returning const& is an
anti-pattern. I like the idea of a compiler warning about it.



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