Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What special rules apply to unary & operator?

Tags:

Are there any special rules that apply to the unary & operator?

For example, the code:

#include <iostream>
struct X
{
    X() {}
    void* operator &() { return NULL; }
};
int main()
{
    const X x;
    std::cout << &x << std::endl;
    X y;
    std::cout << &y;
}

produces the output

0xbfbccb33
0

I knew this would compile and run like this because of a discussion I've had here before, but hadn't I known this, I would have expected this to fail to compile, because operator & is not declared const.

So it appears that the compiler generates operator &() const regardless of whether operator &() is overloaded or not. Fine, this makes sense, especially with the sample and output.

The question is where is this behavior detailed in the standard?

I'm not looking for answers that re-iterate what I already stated in the question, so please don't explain how my overloaded operator can't be called on a const object, because I already know that.

like image 260
Luchian Grigore Avatar asked Oct 22 '12 08:10

Luchian Grigore


People also ask

What is the correct example of a unary operator?

Which is the correct example of a unary operator? Explanation: &, == and / requires two operands whereas — requires only one operand, in general, it decreases the value of operand by 1.

What is the use of unary operator?

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.

What is the symbol of unary operator?

This operator is represented by the symbol, "T," where T is the type to which the operand or the result of the expression must be converted.

What is a unary operator in C?

These are the type of operators that act upon just a single operand for producing a new value. All the unary operators have equal precedence, and their associativity is from right to left. When we combine the unary operator with an operand, we get the unary expression.


1 Answers

n3337 13.3.1.2/9

If the operator is the operator ,, the unary operator &, or the operator ->, and there are no viable functions, then the operator is assumed to be the built-in operator and interpreted according to Clause 5.

like image 149
ForEveR Avatar answered Sep 22 '22 14:09

ForEveR