stringstream::str copy lifetime

后端 未结 3 673
粉色の甜心
粉色の甜心 2020-12-20 04:24

Something a lot of C++ programmers miss (read: me) when first using stringstreams is the fact that the copy returned by stringstream::str() is a te

3条回答
  •  眼角桃花
    2020-12-20 05:05

    This is not a problem of stringstream. It is the problem of c_str function - it returns pointer to a char* representation of std::string, but it lives only during lifetime of an original string. When you call char *str = ss.str().c_str() the following actually happens:

    string tmp = ss.str();
    char *str = tmp.c_str();
    tmp.~string (); // after that line the pointer `str` is no longer valid
    

    c_str is a dangerous function provided only for compatibility and speed purposes and you should avoid using it.

提交回复
热议问题