Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does unary operator & not require a complete type?

The following code compiles fine with both gcc 7.2.0 and clang 6.0.0.

#include <iostream>

struct stru;

void func(stru& s) {
  std::cout << &s << std::endl;
}

int main() {

}

I'm wondering how this is OK. What if stru has overloaded operator&()? The compiler should not be able to tell with simply a forward declaration like struct stru. In my opinion, only std::addressof(s) is OK with an incomplete type.

like image 400
Lingxi Avatar asked Apr 03 '18 07:04

Lingxi


People also ask

Why do we use unary operators?

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.

Why ++ is a unary operator?

Unary Increment (++) In this type, the Unary Operator is denoted by the '++' sign. It increases the value by 1 to the operand and then stores the value to the variable. It works for both Prefix and Postfix positions.

Why is it called a unary operator?

In mathematics, an unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : A → A, where A is a set. The function f is a unary operation on A.

What is meant by unary operator?

What Does Unary Operator Mean? A unary operator, in C#, is an operator that takes a single operand in an expression or a statement.


Video Answer


1 Answers

What if stru has overloaded operator&()?

Then it is unspecified whether the overload will be called (See Oliv's comment for standard quote).

How could unary operator & does not require a complete type?

That's how the standard has defined the language. The built-in address-of operator doesn't need to know the definition of the type, since that has no effect on where to get the address of the object.

One consideration for why it is a good thing: Compatibility with C.

like image 55
eerorika Avatar answered Oct 08 '22 16:10

eerorika