If I define a pointer to an object that defines the []
operator, is there a direct way to access this operator from a pointer?
For example, in the following code I can directly access Vec
's member functions (such as empty()
) by using the pointer's ->
operator, but if I want to access the []
operator I need to first get a reference to the object and then call the operator.
#include <vector>
int main(int argc, char *argv[])
{
std::vector<int> Vec(1,1);
std::vector<int>* VecPtr = &Vec;
if(!VecPtr->empty()) // this is fine
return (*VecPtr)[0]; // is there some sort of ->[] operator I could use?
return 0;
}
I might very well be wrong, but it looks like doing (*VecPtr).empty()
is less efficient than doing VecPtr->empty()
. Which is why I was looking for an alternative to (*VecPtr)[]
.
(*VecPtr)[0]
? – Hl(*VecPtr).empty()
andVecPtr->empty()
are exactly the same thing (unless VecPtr is something that overloadsoperator*
andoperator->
with conflicting meaning. – MerrittVecPtr
is a pointer type, then(*VecPtr).XXX
is, by definition, equivalent toVecPtr->XXX
. There is no loss of efficiency. IfVecPtr
is a non-pointer type that implementsoperator*
andoperator[]
, then you'll have to examine them to see which is more efficient (they are probably the same). – Hl