c++ - 从构造函数C++返回后丢失成员变量的值

标签 c++

这是我正在处理的代码示例。

头文件有以下代码:

class TestClass
{
  private:
    LPCWSTR m_variable;
  public:
    TestClass(const std::string& variable);
}

实现如下:

TestClass::TestClass(const std::string& variable)
{
  std::wstring stemp = std::wstring(variable.begin(), variable.end());
  m_variable= stemp.c_str();
}

下面是调用的代码

std::string tempStr = "Panda";
TestClass *test = new TestClass(tempStr);

我单步调试调试器,发现在构造函数中值看起来不错 L"Panda"。但是一旦我退出调试器,我就再也看不到变量的数据了。

最佳答案

stemp.c_str() 返回一个指向字符串内容的非拥有指针。而拥有支持 .c_str() 结果的数据的 std::wstring stemp 在您从构造函数返回时就不再存在。

更改您的类以直接存储 const std::wstring,这样您就有了该字符串的自有持久拷贝。然后,您可以在需要 LPCWSTR 时安全地对该成员调用 .c_str():

class TestClass
{
  private:
    const std::wstring m_variable;
  public:
    TestClass(const std::string& variable);
}

TestClass::TestClass(const std::string& variable) : m_variable(variable.begin(), variable.end()) {}

关于c++ - 从构造函数C++返回后丢失成员变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471837/

相关文章:

c++ - ElGamal 加密示例?

c++ - VTK - 计算渲染场景的点云

c++ - 更高效地编写 if 语句

c++打印包含结构的 vector

c++ - 关于 boost::unique_future 的文档

c++ - 通过修改时间获取目录下的文件

c++ - 从文件加载多维数组

c++ - Visual Studio 自动设置下一行花括号格式

c++ - 初始化类 - 未解析的外部符号

c++ - 调用 glDrawElements 导致访问冲突