Two reference functions

S

shuisheng

Dear All,

I found there are two functions to reference an element in a
std:vector.

TYPE& operator[]( size_type index );
const TYPE& operator[]( size_type index ) const;

I am wondering why the second is needed. Seems we can always use the
first one to do what we want.

Thanks,

Shuisheng
 
M

Marcus Kwok

shuisheng said:
I found there are two functions to reference an element in a
std:vector.

TYPE& operator[]( size_type index );
const TYPE& operator[]( size_type index ) const;

I am wondering why the second is needed. Seems we can always use the
first one to do what we want.

If the std::vector is const, then you cannot use the first one. Only
const member functions can be called on a const object.

Even if the actual vector itself is not const, it may be "locally"
const, e.g., if it is passed by const reference to a function.
 
F

Frederick Gotham

shuisheng posted:
TYPE& operator[]( size_type index );
const TYPE& operator[]( size_type index ) const;


If TYPE is a something like a function pointer, or a pointer to an array, or
anything more complex than a simple type such as "int" or "short*", then the
code is broken, e.g.:

#define TYPE int (*(*)())[5]

If TYPE is a typedef, then it will work OK -- but evidently it's a macro
since you have used ALL CAPS for its name.
 
H

Howard

Frederick Gotham said:
shuisheng posted:
TYPE& operator[]( size_type index );
const TYPE& operator[]( size_type index ) const;


If TYPE is a something like a function pointer, or a pointer to an array,
or
anything more complex than a simple type such as "int" or "short*", then
the
code is broken, e.g.:

#define TYPE int (*(*)())[5]

If TYPE is a typedef, then it will work OK -- but evidently it's a macro
since you have used ALL CAPS for its name.

Frederick,
Perhaps you didn't notice that Shuisheng said this was in std::vector?
I assume those are the actual template function signatures, and that TYPE is
the template parameter for the type of object stored in the vector.

-Howard
 
F

Frederick Gotham

Howard posted:
Frederick,
Perhaps you didn't notice that Shuisheng said this was in
std::vector?
I assume those are the actual template function signatures, and that
TYPE is the template parameter for the type of object stored in the
vector.


Yes, that seems likely. However I would be extra sure to remind people to
only use ALL CAPS for macros.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top