Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从构造函数C+返回后丢失成员变量的值+;_C++ - Fatal编程技术网

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

C++ 从构造函数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.be

这是我正在编写的代码示例

头文件包含以下代码:

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()) {}
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()) {}

LPCWSTR
不存储字符串;它只是指向ONE.Sou-NoTe:在现代C++中,需要使用<代码>新< /COD>非常罕见。很可能你真的想要
TestClass测试{tempStr}
直接在适当的位置构建它(如果您需要将所有权传递给其他人,请使用
std::move
;如果有人暂时需要您提供非所有权指针,请使用
&
),或者如果您确实需要指针,请使用基于智能指针的方法,如
auto test=std::make_shared(tempStr)
自动测试=std::使_唯一(tempStr)。原始指针是等待发生的内存泄漏。是的,我完全同意,但是我试图与现有代码保持一致。A
LPCWSTR
不存储字符串;它只是指向ONE.Sou-NoTe:在现代C++中,需要使用<代码>新< /COD>非常罕见。很可能你真的想要
TestClass测试{tempStr}
直接在适当的位置构建它(如果您需要将所有权传递给其他人,请使用
std::move
;如果有人暂时需要您提供非所有权指针,请使用
&
),或者如果您确实需要指针,请使用基于智能指针的方法,如
auto test=std::make_shared(tempStr)
自动测试=std::使_唯一(tempStr)。原始指针是等待发生的内存泄漏。是的,我完全同意,但我试图与现有代码保持一致。