简体   繁体   中英

Overloading unary operator &

Let's consider a class with overloaded unary operator & (Address-of). Let it be class A

template <class C>
class A
{
public:
    C * operator &()
    {
        return &data;
    }
    //...
private:
    C data;
}

Now I want to pass to some function a pointer of type A to fill its data . Let us call it f

void f(A * auto_containter)
{
    //...
}

But it is clear why the code bellow wouldn't work (even wouldn't compile). It is because the overloaded operator is called.

A a;
f(&a);

The question is following:

Is there any syntax to pass address of a to f ? If no, then for me it is very strange why it is allowed to overload unary operator & , because it makes code more buggy and difficult to understand. Or there are some other reasons?

Is there any syntax to pass address of a to f ?

Yes, there's ugly syntax:

f( reinterpret_cast<A*>( &reinterpret_cast<char&>(a) ) );

boost::addressof is a nice and generic wrapper around it.

Use boost::addressof function. In any case, overloading unary & is highly dubious. Why do it instead of having a named function that returns the address of your data?

Is there any syntax to pass address of a to f?

Others have already pointed out boost::addressof . The mechanism it relies on is a standard-guaranteed use of the built-in address operator for a reinterpret_cast to reference type. The Boost function just wraps the rather verbose and awkward combination of casts.

If no, then for me it is very strange why it is allowed to overload unary operator &, because if will make code more buggy and difficult to understand. Or there are some other reasons?

In some cases it can be more convenient. For example, a smart pointer class might offer a custom address operator in order to support writing &p as actual argument to a T** formal argument. However, I think nowadays it's generally recognized that it isn't all that good an idea.

Cheers & hth.,

Why would you ever want to overload the unary operator& ?

Aside from that, there is boost::addressof .

这就是为什么发明了boost::addressof原因。

Your scenario never really comes up, because anyone who is writing that function will take a reference, not a pointer. Plus, you forgot to instantiate A with an example type for C.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM