c++ - 在这种情况下如何释放内存?

标签 c++ function class memory-management memory-leaks

我有一个 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时如何释放内存?

最佳答案

我完全看不出所有动态分配的原因,但是您需要删除 func 中的A:

bool func(std::string* stringOut)
{
   A* obj_A = CreateA();                //memory allocated in heap
   *stringOut = obj_A->GetString();
   delete obj_A;                      // delete dynamically allocated object
   return stringOut->empty();    
}

编辑 由于您无法更改CreateA,您至少可以通过使用智能指针(例如std::unique_ptr)使此异常安全或 boost::scoped_ptr。例如:

bool func(std::string* stringOut)
{
   std::unique_ptr<A> obj_A(CreateA());
   *stringOut = obj_A->GetString();
   return stringOut->empty();    
}

关于c++ - 在这种情况下如何释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21890280/

相关文章:

c++ - 当 QDialogs show() 时保持 QMainWindow 最小化

c++ - 我可以在 fnc def 中使用 using 吗?

c++ - 重载类函数运算符两次作为 setter 和 getter

c++ - FFT 与 DFT 有何不同?如何用 C++ 实现它们?

java - 调用Class类型对象的方法

ruby 封装

function - Julia 在调用之前覆盖函数

javascript - Qunit 不可见的函数

PHP - 将点后或点和空格后的首字母大写

ios - 重用类最佳实践