Reputation: 2287
I have defined a (const) tuple as follows:
double var1, var2;
const tuple<double&, double&> my_tup(var1, var2);
Now, why am I able to do the following:
get<0>(my_tup) = 3215.513
The above code would only make sense if the references contained in the tuple are const
pointers to var1 and var2 - the memory address itself is const
(because the tuple is const
, so we cannot change any of its contents), but the contents of the memory addresses pointed to, not, hence the allowed change. But, if you look at this discussion about what references really are, you will see there are some fervent advocates for the reference not being a const
pointer, but just a different name for a variable already declared. In that case, how can I interpret a const
tuple of references? Is declaring the tuple as const
above, if it contains references, pointless then?
(Note that I had to use a const
tuple in another setting, which is too complicated to explain and irrelevant to the question.)
Upvotes: 3
Views: 2463
Reputation: 119229
If a class object is const
, then its data members are implicitly const
too (unless declared mutable
). So, in general, if a tuple is const
, then none of its members can be modified.
However, a reference cannot be const
(only the referenced type can be). Indeed, a reference itself cannot be modified anyway (any attempt to do so modifies the object referred to). Since a reference cannot be const
, the members of your const
tuple still have type double&
, not const double&
, and the const
on your tuple
is pretty meaningless in this case. What you really want is tuple<const double&, const double&>
.
Upvotes: 4