+ 2
Operator -> for shared pointer
Hi I have a member variable T* m_ptr into templated class. This is in line with shared pointer implementation. My query is operator overloaded function as below: T* operator->() { return m_ptr; } Why this pointer directly call method ? Should it not be mysharedptr->->mymethod() Double time -> is not needed?
6 Respuestas
+ 3
when "operator->" returns, the "operator->" is applied to the value returned, with the original second operand.
so :
"bptr->display(); "
translates into:
"(bptr.operator->())->display();"
chained calls of ".operator->()" can be reduced to a single "->" .
C++98 standard §13.5.6/1 "Class member access:
"
An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism.
"
+ 1
Thanks
+ 1
-> was not available to use before you overloaded it. How can there be the first -> in '->->' ? If you can already use ->, why is there the need to define an operator overlaod in the first place?
+ 1
MO ELomari
nice.
+ 1
MO ELomari thanks
0
T* operator->() const is the concern here for me.
This is called from last line of the main function.
bptr->display() results into printing display by calling a function display.
Now comes tricky part.
bptr is object of class custom shared pointer. Overloaded -> operator I.e. bptr-> will gives us T* from class member. This T* should need now another -> to call display method.
In other word , Should it not be (bptr->)->display()?
https://sololearn.com/compiler-playground/chbZHAzzB0Rz/?ref=app