0

我的类.h

#pragma once

class MyClass {
public:
    const char* m_var;
    MyClass();
};

我的类.cpp

#include <iostream>
#include <sstream>
#include "MyClass.h"

MyClass::MyClass() :
    m_var(("Text_" + std::to_string(5)).c_str())
{}

主文件

#include <iostream>
#include "MyClass.h"

int main()
{
    MyClass myClass;
    std::cout << myClass.m_var;
    std::cin.get();
}

我期待程序输出Text_5,而不是输出:

╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠​ ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠⌠╠╠╠╠╠╠╠╠

4

1 回答 1

3

不要这样做。不要试图存储.std::string::c_str()

子表达式

"Text_" + std::to_string(5)

产生一个临时 对象,在执行完整表达式后std::string立即自动销毁

("Text_" + std::to_string(5)).c_str()

当该对象被销毁时,由's 结果"Text_5"指向的C 字符串也被销毁。c_str()因此,您的m_var指针最终指向无处。您看到的打印内容是来自那个“无处”的垃圾。该行为在形式上是未定义的。

例如,这将“按预期”工作

std::cout << ("Text_" + std::to_string(5)).c_str() << std::endl;
// The temporary is destroyed at the end of the full expression. 
// It lives long enough to make the above output succeed.

但这不会

const char *str = ("Text_" + std::to_string(5)).c_str();
// The temporary is destroyed at the end of the above expression. 
// Here it is already dead, meaning that `str` is an invalid pointer
// and the output below will not work
std::cout << str << std::endl;

这将再次“按预期”工作

std::string s = "Text_" + std::to_string(5);
const char *str = s.c_str();
// Since `s` is not a temporary, it is not destroyed here, `str` remains 
// valid and the output below works
std::cout << str << std::endl;

但无论如何,不​​要试图将结果c_str()用于长期存储。如果您正在处理临时对象,则根本不要考虑存储它。它旨在仅用于片刻,最好在单个表达式中使用。如果您存储由 返回的指针c_str(),您可能会突然发现它在您不注意的情况下变得无效。形式上,只要您真的知道自己在做什么,就可以将该指针保留一段时间。但是你上面有一个教科书的例子,说明它什么时候失败了。

于 2017-10-31T06:18:42.430 回答