c++ - 从函数返回前释放 unique_ptr

标签 c++ visual-studio-2010 smart-pointers

我正在使用 unique_ptrconst wchar_t 指针传递给函数。下面我想举一个简短的例子:

bool MyClass::foo(unique_ptr<const wchar_t> display_name) {
  bool result = false;
  ....
  // Do something
  result = DoWork(display_name.get());
  ....
  // I have to call release to prevent getting an error
  display_name.release();
  return result;
}

直到现在我认为我不必在离开作用域(从函数返回)之前调用 unique_ptrrelease() 方法,因为如果 unique_ptr 超出范围,unique_ptr 将被自动删除。但是,如果不调用 release() 方法,我会收到以下错误 (VS 2010):

enter image description here

我认为出现此错误消息是因为未正确释放内存?处理作为参数传递的 unique_ptr 的推荐方法是什么?

最佳答案

根据您的描述和评论,我相信这更符合您的需求:

bool MyClass::foo(const std::wstring& display_name)
{
  bool result = false;

  // Do something
  result = DoWork(display_name.c_str());

  return result;
}

此字符串对象是 wchar_t 的 STL 容器,具有各种有用的方法。其中之一是 c_str(),它返回字符串内容的 c 风格 const wchar_t* 版本,以便与旧代码向后兼容。您的 DoWork 函数可能是这样一个函数,它需要一个 c 风格的字符串,所以上面的内容对您有用。


现在进入智能指针 101:

在 C++11 中,std::unique_ptr 可用于自动销毁堆上分配的对象,免除异常不安全代码和手动内存管理可能导致内存泄漏和其他问题的担忧坏事。假设您有以下代码:

void LeakyFunction()
{
    double* ptr = new double;
}

显然这是内存泄漏,因为一旦 LeakyFunction 的作用域结束,我们就失去了堆栈上的指针,并且无法再删除它在堆上指向的内容。所以我们这样写:

void LessLikelyLeakyFunction()
{
    double* ptr = new double;
    // do stuff
    delete ptr; // clean up heap
}

这很好而且花花公子,除非您提前返回或在代码的 do stuff 部分抛出异常,这会使您回到与以前相同的问题。所以人们开始编写自定义智能指针类,它通过在构造时分配和在销毁时释放来拥有原始内存分配。这个概念现在已经通过 std::unique_ptr 之类的东西成为标准,因此我们可以执行以下操作:

void SmartFunction()
{
    std::unique_ptr<double> ptr(new double);
    // do stuff
} // unique_ptr is smart and calls delete for you

这样,无论函数作用域何时结束,您都不必担心事情会被正确清理。 简而言之,如果您不使用 new,则不需要智能指针;如果您需要,那么您可能应该使用智能指针来使您的代码更健壮。

关于c++ - 从函数返回前释放 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8661394/

相关文章:

c++ - 错误 C++ 2679(二进制 '>>' : no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion))

c++ - 如何使msvc向量化浮点加法?

c++ - std::unique_ptr 不能被引用——它是一个被删除的函数

c++ - 轮询事件API的设计

c++ - 我不明白我为这个程序得到的输出。

c++ - 在 Visual Studio 2010 中将项目从 Win32 移植到 x64 平台后加载了不正确的 ComCtl32.dll

visual-studio-2010 - 我可以在 C# 4 中实现 method_missing 并让它实际返回一个值吗?

sql - 程序使用哪些文件?

c++ - 用于智能指针的 std::atomic 的部分模板特化

c++ - 如何将 gmock SaveArgPointee 与派生类的 std::shared_ptr 一起使用