字符串流str和成员变量的生命周期

时间:2019-05-06 13:45:15

标签: c++ address-sanitizer

当尝试从由存储在类内的成员中的stringstream创建的str对象中打印字符串时,我得到了ASAN的堆后释放错误:

const char* MyClass::somefunction() const throw()
{
   std::stringstream msg;

   // print some stuff into the stringstream

   m_Member = msg.str();
   return m_Member.c_str();
}

m_Member的类型为可变std :: string(不是引用)。

某些函数的返回值会立即移交给其他尝试打印它的函数。此打印尝试会导致释放后使用堆:

MyClass object;
printFunction( object.somefunction() );

根据ASAN,printFunction尝试访问stringstream类中由msg.str()调用分配的地址,然后使用basic_string析构函数中的msg.str()再次销毁该地址。

我对msg.str()返回的对象的生存期做出错误的假设吗?

编辑:好的,还有一个细节:MyClass实际上是一个异常类,并且在异常发生后在catch块中打印错误时发生错误:

try
{
    // throws exception of type MyClass
}
catch ( MyClass& exception)
{
   printFunction( exception.somefunction() );
}

m_Member是异常类的成员。

0 个答案:

没有答案