I am trying to understand the following case, which behaves differently from what I expect.
Given the 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 would expect the call constDeque.emplace_back(1ULL);
to fail, since I am expecting constDeque
to be a reference to a const std::deque<>
, but it actually compiles without any error on GCC 5.4.0.
If I change the line above to const auto constDeque = constTestClass.getDeque();
it fails to compile as expected, since constDeque
now is of the expected type.
I am trying to understand why auto
can remove the const-ness from the return type and where the error in my understanding lies.
EDIT: This is not answered as a duplicate. I am still looking for a way to make sure the caller always gets a const reference (or pointer) to the internal object, so the caller will see state changes to the itnernal object without being able to modify it.