c++ - Returning a const pointer to a const data member and the 'auto' keyword. A bit confused -
i've been learning c++ , today have been introduced const , concept of const correctness. in attempt better understand theory, i've been writing series of simple programs make sure understand concept correctly. thought understood everything, when using auto keyword in 1 of programs, seem have got bit stuck.
in order test understood how const pointers work wrote simple program. won't bother posting whole thing since there's 2 parts of relevant. have class const data member of type int:
const int trytochangeme;
within class have member function returns const pointer above const int:
const int* const myclass::test() { return &trytochangeme; }
in main function call above function, making use of auto keyword. in order test think know const correct attempt reassign trytochangeme variable through pointer. so:
auto temp = myclass.test(); *temp = 100;
as expected, program wouldn't compile due error caused when trying assign value const variable. however, didn't return pointer const, returned const pointer const (at least that's thought did). test this, attempted reassign pointer new memory address, quite confident i'd similar compilation error:
temp = new int;
but quite confusingly program compiled without issue. stepping through debugger revealed sure enough, pointer losing original address , being assigned brand new one. wondering going on, happened chance remove auto keyword , replace variable's full type:
const int* const temp = myclass.test();
upon testing again, results expected , time not able reassign pointer new address.
so after guess question is, why? why auto keyword allow bypass const qualifier of pointers? did wrong?
by way, i'm not sure if matters i'm using visual studio 2015 preview
as mentioned, auto
ignores top level cv-qualifiers. read this article learn details of how auto
, decltype
work.
now, if auto
didn't ignore const
, in case, temp
still not const
because top level cv-qualifiers on return types ignored if type being returned of non-class type.
g++ produces following warning -wextra
warning: type qualifiers ignored on function return type [-wignored-qualifiers]
this can demonstrated using c++14's decltype(auto)
. unlike auto
, decltype(auto)
doesn't discard references , top level cv-qualifiers. if modify example adding following lines code still compile, proving temp
not const
pointer.
decltype(auto) temp = myclass.test(); static_assert(std::is_same<const int*, decltype(temp)>{}, "");
on other hand, if test()
returns object of class type top level cv-qualifier, auto
still discard const
, decltype(auto)
wouldn't.
Comments
Post a Comment