C++ 常量字符*常量因字符串(?)而更改
您好,我正在构建一个项目,今天在完成500行代码后,我将拍摄我自己。今天我开了一门新课,发生了一些非常奇怪的事情:C++ 常量字符*常量因字符串(?)而更改,c++,c++11,C++,C++11,您好,我正在构建一个项目,今天在完成500行代码后,我将拍摄我自己。今天我开了一门新课,发生了一些非常奇怪的事情: class Target { public: Target(const int port); virtual ~Target(); private: const char* initialize_port(const int port) const; const char *const port; }; 和cpp文件: Target::Target(const
class Target {
public:
Target(const int port);
virtual ~Target();
private:
const char* initialize_port(const int port) const;
const char *const port;
};
和cpp文件:
Target::Target(const int port)
:
port(initialize_port(port))
{
cout<<this->port<<endl; //this cout 80
string test3="Target2";//when i replace with char * test3="Target2" then both couts in the constructor are working ok.
cout<<this->port<<endl; //this cout Target2!!!!!!
}
const char* Target::initialize_port(const int port) const {
string port_str = std::to_string(port);
const char* port_char=port_str.c_str();
return port_char; // OR/and when i replace with something like return "80" then both couts in the constructor are working ok.
}
Target::~Target() {
}
Target::Target(常量int端口)
:
端口(初始化_端口(端口))
{
cout问题来自:
{
string port_str = std::to_string(port);
const char* port_char=port_str.c_str();
return port_char;
}
当返回
时,port_str
被销毁,因为它是该代码块的区域变量。然后port_char
是一个悬空指针(用于指向现在已销毁的对象的指针)
使用该指针会导致未定义的行为,这就解释了使用指针时的奇怪效果
要解决此问题,请停止使用原始指针。最简单的解决方法是使用std::string
。问题是port\u str.c\u string()的返回值
仅在port\u str
的生存期内有效。由于该值在initialize\u port
中的堆栈上分配,因此一旦该函数返回,该值将无效
在构造函数中,当初始化test3
字符串时,它最终(大部分是偶然的)占用了与port_str相同的内存
如果需要使用const char*,则需要为initialize_端口内的字符串分配新内存(并在构造函数中取消分配!)。或者继续使用std:string对象。如果你想存储字符串,请使用string
。你有一个悬空的指针和未定义的行为。抱歉,与这里发布的任何具体问题的诊断无关!我真诚地希望“今天,在500行代码之后,我将自杀”只是一个不正确的翻译??@πάνταῥεῖ 有趣的昵称。但它不是“总是流动”。你的昵称不是古老的座右铭。很可能你想说“απάνταρε”,意思是“一切都在流动”.细微的差别会改变意思。有时答案也会改变;-)@DimopoulosElias我怀疑你作为一个以英语为母语的人比我更能判断这句座右铭。总之你很好,我的行为有时不可靠;-)。。。