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

前端 未结 3 1971
礼貌的吻别
礼貌的吻别 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.

    0 讨论(0)
  • 2020-12-01 23:57

    Interesting little question. According to the C++11 standard, sect. 21.4.2.9,

    basic_string(const charT* s, const Allocator& a = Allocator());
    

    Requires: s shall not be a null pointer.

    Since the standard does not ask the library to throw an exception when this particular requirement is not met, it would appear that passing a null pointer provoked undefined behavior.

    0 讨论(0)
  • 2020-12-01 23:58

    My question is if GetValue() returns NULL myString becomes an empty string? Is it undefined? or it will segfault?

    It's undefined behavior. The compiler and run time can do whatever it wants and still be compliant.

    0 讨论(0)
提交回复
热议问题