c++ - const_cast a const member in a class constructor -
i use const_cast when want member variable of class constant during life of class, needs mutable during constructor. example:
struct qqq { const vector<foo> my_foo; qqq(vector<foo>* other) { vector<foo>& mutable_foo = const_cast<vector<foo>&>(my_foo) other->swap(mutable_foo); } }; i had assumed doing in constructor ok because nobody else relying on @ point wouldn't interact badly optimization, etc.
however told me "undefined behavior" , it's illegal mutate const object after it's been constructed under circumstance.
can clarify? bad / undefined behavior / thing do?
it undefined behavior. per paragraph 7.1.6.1/4 of c++11 standard:
except class member declared
mutable(7.1.1) can modified, attempt modifyconstobject during lifetime (3.8) results in undefined behavior.
in case, seems want object "become" constant after construction. not possible.
if vector meant const, shall initialize in constructor's initialization list:
qqq(vector<foo>& other) : my_foo(std::move(other)) // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ { } notice, unless have reason passing pointer - in case, should checking whether pointer non-null - should consider passing reference (as shown above), common practice.
update:
as pete becker correctly points out in comments, proper design suggest decision move vector argument should belong caller of qqq's constructor, , not constructor itself.
if constructor supposed move argument, let accept rvalue reference, making clear constructor expecting out of caller:
qqq(vector<foo>&& other) // ^^ : my_foo(std::move(other)) // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ { } this way, caller have provide rvalue in input qqq's constructor:
std::vector<foo> v; // ... qqq q1(v); // error! qqq q2(std::move(v)); // ok! client aware v must moved
Comments
Post a Comment