简体   繁体   中英

Losing value of member variable after returning from constructor C++

Here is the code sample I am working on.

Header file has below code:

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

Here is the implementation:

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

Here is the code how I make the call

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

I stepped through debugger and see that while in constructor the value looks good L"Panda" . But as soon as I step out of debugger I no longer see the data for my variable.

stemp.c_str() returns a non-owning pointer to the contents of the string. And std::wstring stemp , which owns the data backing the result of .c_str() , ceases to exist the moment you return from the constructor.

Change your class to store a const std::wstring directly, so you have an owned, persistent copy of the string. You can then safely call .c_str() on the member whenever you need a LPCWSTR :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM