Is using NULL references OK?

前端 未结 7 1409
一整个雨季
一整个雨季 2020-12-05 20:37

I came across this code:

void f(const std::string &s);

And then a call:

f( *((std::string*)NULL) );

A

7条回答
  •  时光取名叫无心
    2020-12-05 20:54

    You will sometimes see constructions like this in fairly esoteric template library code, but only inside a sizeof() where it is harmless.

    Supposing you wanted to know the size of the return type of a function-like type F if it was passed a reference to a type T as an argument (both of those being template parameters). You could write:

    sizeof(F(T()))
    

    But what if T happens to have no public default constructor? So you do this instead:

    sizeof(F(*((T *)0)))
    

    The expression passed to sizeof never executes - it just gets analyzed to the point where the compiler knows the size of the result.

提交回复
热议问题