0
我有一类A和func
如下如何在这种情况下释放内存?
class A
{
int m_memA;
public:
A(int x):m_memA(x){}
std::string GetString();
};
A* CreateA()
{
return new A(5);
}
bool func(std::string* stringOut)
{
A* obj_A = CreateA(); //memory allocated in heap
*stringOut = obj_A->GetString();
if(stringOut->empty())
{return true;}
return false;
}
int main()
{
std::string str;
if(func(&str)) //How to free memory here?
{
//do something
}
return 0;
}
如何释放内存,一个功能时func
被称为?
CreateA(),类A是预先存在的代码。对此无能为力。 func是在我的控制之下。 – ontherocks
@ontherocks好的。使用智能指针可能是更好的选择。看我的编辑。 – juanchopanza
所以在'* stringOut = obj_A-> GetString();'stringOut有返回字符串集(因为它被解除引用?)。所以删除obj_A后,不会导致无效指针。 – ontherocks