Assign a nullptr to a std::string is safe?

前端 未结 3 1989
礼貌的吻别
礼貌的吻别 2020-12-01 23:35

I was working on a little project and came to a situation where the following happened:

std::string myString;
#GetValue() returns a char*
myString = myObject         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 23:52

    It is runtime error.

    You should do this:

    myString = ValueOrEmpty(myObject.GetValue());
    

    where ValueOrEmpty is defined as:

    std::string ValueOrEmpty(const char* s)
    {
        return s == nullptr ? std::string() : s;
    }
    

    Or you could return const char* (it makes better sense):

    const char* ValueOrEmpty(const char* s)
    {
        return s == nullptr ? "" : s; 
    }
    

    If you return const char*, then at the call-site, it will convert into std::string.

提交回复
热议问题