c++ - Passing const reference leads to paradox in code..? -
ok have function within class named vector_ref
class vector_ref { public: int* data() const { return m_data } void retarget(std::vector<int> const& _t) { m_data = _t.data(); m_count = _t.size() } private: int* m_data; size_t m_count; }
i trying retarget vector_ref object existing vector object named v populated ints , call data().
vector_ref<int> tmp; tmp.retarget(const_cast<std::vector<int> const&>(v)); tmp.data(); // error here
the pass retarget compiles, calling data() yields error:
invalid conversion const int* int* { m_data = v.data() ... }
this makes sense me, member variable m_data
isn't const
, given class definition how can ever retarget
existing vector
. if have pass const
reference retarget()
, sets non-const
member variable m_data
, how can ever hope compile code retargets vector_ref
instance ?
just declare m_data
as
const int* m_data;
this doesn't mean m_data
const
. means cannot modify int
m_data
points to. can still this:
m_data = _t.data();
but can't this:
*m_data = x; m_data[5] = y; // or
by way, there's no need const_cast
. need const_cast
if removing const qualifier (i.e. passing const
object function expects non-const reference). don't need in order pass non-const object function accepts const reference.
Comments
Post a Comment