+ 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?

23rd Sep 2024, 3:43 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 ответов
+ 1
Thanks
23rd Sep 2024, 4:26 PM
Belzy Hacker(But Friendly)
Belzy Hacker(But Friendly) - avatar
+ 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?
24th Sep 2024, 1:52 AM
Bob_Li
Bob_Li - avatar
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
24th Sep 2024, 3:56 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
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. "
24th Sep 2024, 8:53 PM
MO ELomari
MO ELomari - avatar