
Mark Deric wrote:
"Peter Dimov" <pdimov@mmltd.net> wrote:
struct Dummy { int a; }
class Lock { private: Dummy &_d; public: Lock( Dummy &d ) : _d(d) { std::cout << "Locked." << std::endl; } ~Lock( void ) { std::cout << "Unlocked." << std::endl; }
Dummy *operator->( void ) { return &_d; } };
class Ref { private: Dummy &_d; public: Ref( Dummy &d ) : _d(d) { }
Lock operator->(void) { return Lock(_d); } };
Your code is non-portable. You are assuming that the temporary Lock(_d) will be constructed directly in the return value, but this is not guaranteed.
I'm not sure I'm following "constructed directly in the return value"; but, it will be constructed before the call to Lock's Dummy *operator->( void ) as implied by x->a, below. Isn't this all that is required?
No, because ~Lock will be called twice.