c++ - Const-ness when returning reference to an internal object -
this question has answer here:
i trying understand following case, behaves differently expect.
given following code example:
class consttestclass { std::deque<unsigned long long> deque; public: const std::deque<unsigned long long int> &getdeque() const{return deque;} }; int main() { consttestclass consttestclass; auto constdeque = consttestclass.getdeque(); constdeque.emplace_back(1ull); }
i expect call constdeque.emplace_back(1ull);
fail, since expecting constdeque
reference const std::deque<>
, compiles without error on gcc 5.4.0.
if change line above const auto constdeque = consttestclass.getdeque();
fails compile expected, since constdeque
of expected type.
i trying understand why auto
can remove const-ness return type , error in understanding lies.
edit: not answered duplicate. still looking way make sure caller gets const reference (or pointer) internal object, caller see state changes itnernal object without being able modify it.
auto
uses same rules template argument deduction. in order clarify further, imagine have function (e.g., foo
):
template<typename t> void foo(t v) { v.emplace_back(1ull); }
and following:
std::deque<unsigned long long> dq; const std::deque<unsigned long long> &dqr = dq; foo(dqr);
this code pass compiler live demo. happening because according template argument deduction rules t
deduced std::deque<unsigned long long>
, dqr
passed copy foo
.
now imagine auto
template argument (e.g,. t
):
t constdeque = consttestclass.getdeque();
because auto
uses same rules template argument deduction, happend in example in foo
, deduce t
in std::deque<unsigned long long>
.
consequently, you're creating copy of const
member std::deque
member variable. getting behaviour you're anticipating, you'll have give little auto
deduction , write:
auto &constdeque = consttestclass.getdeque();
or if want clarify further readers of code resulting auto
deduction const
qualified variable add explicitly const
qualifier as:
auto const &constdeque = consttestclass.getdeque();
Comments
Post a Comment