gpt4 book ai didi

c++ - 返回 char* 出错,打印好,返回不好(c++)

转载 作者:行者123 更新时间:2023-11-30 02:33:30 25 4
gpt4 key购买 nike

在这个函数中我需要返回一个 char* 变量,在我返回它之前,我打印它并且它打印得很好。导致返回变量错误的变量发生了什么,为什么?

函数:

const char* NameErrorException::what() const throw()
{
std::string str = "NameErrorException: name \'";
str += _name;
str += "\' is not defimed";
std::cout << str.c_str()<< std::endl; //Prints good
return str.c_str();
}

打印代码:

catch (std::exception& ex)
{
//Prints something like "▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌♀·┘v♦"
std::cout << ex.what() << std::endl;
}

(NameErrorException 异常的继承者)

谢谢!

最佳答案

您的字符串 str 将在您离开该函数后被销毁。所以你返回的指针是无效的,因为它指向由对象处理的内存。如果对象被销毁,它将再次释放此内存。

使 str 成为 Exception 的成员,并在构造函数中对其进行初始化。比你的 what() 将返回一个有效的指针(只要异常对象有效)。

#include <string>
#include <iostream>

class NameErrorException : public std::exception
{
std::string m_what;
public:
NameErrorException(std::string name)
:m_what("NameErrorException: name \'" + name + "\' is not defined")
{
}

const char* what() const throw() override
{
return m_what.c_str();
}
};


int main()
{
try
{
throw NameErrorException("TEST");
}
catch (std::exception& ex)
{
std::cout << ex.what() << std::endl;
}
}

参见此处:http://coliru.stacked-crooked.com/a/878d5835db998300

关于c++ - 返回 char* 出错,打印好,返回不好(c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35360078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com