Copy of const char * using std::string constructor

前端 未结 5 483
鱼传尺愫
鱼传尺愫 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 10:05

    It's ok since it compiles and doesn't cause undefined behavior.

    It's not ok since name points to an invalid memory after the statement completes execution.

    name = std::string(_name).c_str();
    

    At the end of this statement the temporary std::string is destroyed and it frees the memory of c_str().

    should i do an old school strcpy ?

    No, just change name to be std::string:

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

提交回复
热议问题