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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With