Re: rvalue reference factory?
On Tuesday, 13 May 2014 01:50:00 UTC+3, fran...@googlemail.com wrote:
Is it possible in c++11 to have a factory function that returns
rvalue references of base class types?
You typically do not want to make types that are used as dynamically
polymorphic also moveable, copyable, assignable or swappable. You
delete all that of such objects. Otherwise it is bear trap of object
slicing waiting for your own leg there. ;)
Instead you allocate dynamically polymorphic objects dynamically
and use with indirection (likely smart) pointer. If you need copies
then you make them clonable with virtual clone. Move, share or swap
you do by manipulating the pointers, not the objects.
Returning rvalue reference is useless there but may be useful when
programmer wants to move from data member.
struct XFactory
{
X x_; // note, nothing dynamically polymorphic here.
X const& getX() const { return x_; }
X&& getX() { return move(x_); }
};
// usage
X x = XFactory().getX(); // move happens here
It is riskier than returning by value but there may be performance
benefits depending on what that X is. Unsure if returning rvalue
reference is useful for anything else at all.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]