C++ 字符串和 char* 的区别示例

San*_*dze 1 c++ pointers std c-strings char

这是来自 hackerrank“继承代码”的示例,

虽然这有效并what()返回n,但如果我注释返回what并取消注释当前注释的部分what()将返回垃圾。

它们在我看来都一样,有什么区别?

/* Define the exception here */
struct BadLengthException : public exception {      
    public: 
    int num;
    string stra;
    BadLengthException(int n){
        this->num = n;
        this->stra = to_string(this->num);
    };
    
   const char * what () const throw () {

       return this->stra.c_str();


       //string a = to_string(this->num);
       //return  a.c_str();
   }
};
Run Code Online (Sandbox Code Playgroud)

lor*_*rro 7

string a是 中的本地 (ASDV) what()。当你返回时它就超出了范围。a.c_str()只是一个指针,它是非拥有的,因此不会延长 char 缓冲区的生命周期,因此它是 UB。对于 UB,任何事情都可能发生,包括退回垃圾。