Is using NULL references OK?

前端 未结 7 1410
一整个雨季
一整个雨季 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:59

    As others already said: A reference has to be valid. That's why it's a reference instead of a pointer.

    If you want to make f() have a default behavior, you might want to use this:

    static const std::string default_for_f;
    
    void f(const std::string &s = default_for_f)
    {
        if (&s == &default_for_f)
        {
            // make default processing
        }
        else
        ...
    }
    ...
    void bar()
    {
        f();              // call with default behavior
        f(default_for_f); // call with default behavior
        f(std::string()); // call with other behavior
    }
    

    You can spare the default parameter for f(). (Some people hate default parameters.)

提交回复
热议问题