Copy of const char * using std::string constructor

前端 未结 5 505
鱼传尺愫
鱼传尺愫 2021-01-15 09:36

is this code ok?

void SomeClass :: foo(const char * _name) {
     //name is of type const char *
     name = std::string(_name).c_str();
}

5条回答
  •  青春惊慌失措
    2021-01-15 09:59

    If you don't do anything with name, it's perfectly safe. Otherwise, it will probably fail at some random point in the future. The C-style pointer returned by the c_str() member function is only valid for as long as the temporary std::string exists (and as long as you don't mutate it, which you haven't in this case). As soon as the enclosing block scope exits, the temporary is destroyed, and any use of name puts you into the twilight zone.

    As others have suggested, you should turn name into a std::string. Alternatively — if you really need it to stay a char * — you could just write name = strdup(_name).

提交回复
热议问题