Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: unusual operator overloading

What an operator is overloaded here?

operator T * ()

I know that the operator method has the following structure:

type operator operator-symbol ( parameter-list )

Assume we have the following code

template<typename T> class SmartPtr
{
public:
    SmartPtr(T* data): member(data) {}
    T* member;      
    T& operator * () { return *member; }  //usage: *TObj    
    T*& operator () () { return member; }  //usage: TObj()
    operator T * () { return member; }   //usage: ???
};

No compilation errors if you try it on the ideone. So what is going on here?

ADD: Am I right that static_cast<T*>(TObj) makes a call of the operator T *? I've tried it here.

like image 755
yakov Avatar asked Feb 08 '26 01:02

yakov


1 Answers

That's a conversion operator, which allows the class to be converted to T*. Usage:

T * p = TObj;

It's probably a bad idea for a smart pointer to provide this, as it makes it easy to accidentally get a non-smart pointer. Standard smart pointers provide explicit conversion via a get() function instead, to prevent accidental conversions.

like image 143
Mike Seymour Avatar answered Feb 09 '26 14:02

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!