c++ - Force a returned const value to move not copy -
i know ok:
struct foo { foo& operator=( foo& ) = delete; // disallow assign foo( int ) { } // basic constructor foo( const foo& ) = delete; // disallow copy foo( foo&& ) { } // allow move }; foo getfoo( void ) { return foo( 3 ); } foo foo = getfoo( ); // uses move constructor
whereas use copy constructor, , therefore invalid foo
(and object with copy constructor, valid inefficient):
const foo getconstfoo( void ) { return foo( 3 ); } const foo constfoo = getconstfoo( ); // error: copy constructor deleted!
but ok: (and extend life of constfooref
)
const foo& constfooref = getconstfoo( ); // uses move constructor
now, second case call
foo( const foo&& ) { }
if it's available. know if there's way detect final object const
inside constructor. if there is, can apply move semantics (since both involved objects const , parameter isn't being used elsewhere it's ok cast away const-ness), , make second case legal.
so while question title explains end-result i'm trying achieve, sub-problem detecting whether object const after has been constructed (naïvely tried foo( const foo&& ) const { }
, no luck there!)
you might do
foo::constant getconstfoo( void ) { return foo::constant( 3 ); }
where foo::constant immutable
struct foo { struct constant { constant(foo&&); }; foo& operator=( foo& ) = delete; // disallow assign foo( int ) { } // basic constructor foo( const foo& ) = delete; // disallow copy // might not use: foo( foo&& ) { } // allow move };
Comments
Post a Comment