Overloading unary operator &

不羁岁月 提交于 2019-12-29 06:39:25

问题


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?


回答1:


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?




回答2:


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.




回答3:


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.,




回答4:


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

Aside from that, there is boost::addressof.




回答5:


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.




回答6:


This is why boost::addressof was invented.



来源:https://stackoverflow.com/questions/6410333/overloading-unary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!