c++ - std::move( ) calls copy-ctor in the absence of a move-ctor. Why and how to prevent it? -
i want know if there safe programming practice alert coder subtle behavior when takes place or, better, avoid in first place.
a user of struct a might not realize there no move constructor. in attempt call absent ctor neither compiler warning or run-time indication copy ctor called instead.
an answer below explains conversion takes place don't see rationale being thing. if constructor taking const reference parameter missing there compile time error rather resolving non-const reference version. why wouldn't attempt @ using move semantics result in compile time error when there no move semantics implemented in class?
is there way avoid behavior compile time option or @ least way detect during run time?
one assert(source null) after move if anticipating problem true of many problems.
example, when:
struct { a() {...} a(a &a) {...} a(a const & a) {...} }; is constructed in:
a a1; a2 = std::move(a1); //calls const copy (but how know?) this results in const version of copy ctor being called. 2 objects might have pointer single resource while 1 of them calling it's destructor soon.
since std::move returns rvalue, convertible const ref why copy ctor being silently called. can fix several ways.
- easy way, if class has no dynamic allocation use default mctor this.
a(a &&) = default; get rid of const in cctor, prolly not idea won't compile
just implement own move constructor, why moving object if has no mctor
this off topic can qualify member function work modifiable lvalue this.
int func()&;
if dealing legacy code here compile time check move constructable
Comments
Post a Comment