Quantcast
Channel: User Peter - Reinstate Monica - Stack Overflow
Viewing all articles
Browse latest Browse all 223

Answer by Peter - Reinstate Monica for Why does "int *find(const vector&vec, int value)" give me an invalid conversion error?

$
0
0

Well, the idea is that not only is the vector constant but the standard library designers figured that the most reasonable semantics for a constant vector object is that its data is treated as constant as well. (This is not self-understood: The data is quite distinct from the vector object, the vector holds only a pointer to it.)

This is reflected in the two std::vector<T,Allocator>::operator[] versions, one for "normal" vectors and the other one for "const" ones. The notation indicating that a member function is defined and will be selected for constant objects is a trailing const in the member function declaration:

reference operator[]( size_type pos );const_reference operator[]( size_type pos ) const; // for const vectors

The const version also differs in its return type. It returns a const_reference which is defined in the vector as const value_type&, a const reference to the element type T with which the vector was instantiated.

And if we remember that taking the address of a reference (here: the one returned by operator[]) is the address of the referenced object we see that the address of a reference to const is the address of a const, in your case of a const int. That address cannot be assigned to a pointer to an ordinary int because that pointer would allow an inadvertent write access to the constant object.


Viewing all articles
Browse latest Browse all 223

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>