c++11 - Forcing the copy constructor -
i have function this:
object class::function() { object o; return o; }
now when call this:
object o = class::function();
it wants use move constructor. want use copy constructor. how force not use move constructor? deleted move constructor won't compile.
edit: constructors this:
object(const object & other) { ... } object(object & other) { ... } object(object && other)=delete;
if have user-declared (manually declared) copy ctor, move ctor not declared implicitly. leave out move ctor, , won't take part in overload resolution (i.e. don't define deleted, leave out entire declaration).
after cwg dr 1402, explanation different: move ctor declared if there's user-declared copy ctor, implicitly defined deleted. , there's special case deletion makes move ctor not take part in overload resolution. note: if explicitly delete move ctor, still means "if function selected overload resolution, program ill-formed". special case applies when move ctor defaulted (explicitly or implicitly), , when leads move ctor being defined deleted (as implicit definition supplied defaulted function).
#include <iostream> struct loud { loud() { std::cout << "default ctor\n"; } loud(loud const&) { std::cout << "copy ctor\n"; } loud(loud&&) { std::cout << "move ctor\n"; } ~loud() { std::cout << "dtor\n"; } }; struct foo { loud l; foo() = default; foo(foo const& p) : l(p.l) { /*..*/ }; // or `= default;` // don't add move ctor, not deleted! }; foo make_foo() { return {{}}; } int main() { auto x = make_foo(); }
watch out copy elision (e.g. use -fno-elide-constructors
). output:
default ctor copy ctor dtor dtor
Comments
Post a Comment