从函数返回之前释放 unique_ptr

发布于 2024-12-23 08:38:34 字数 726 浏览 4 评论 0原文

我使用 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):

在此处输入图像描述

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

I'm using a unique_ptr to pass a const wchar_t pointer to a function. In the following I would like to give a short example:

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;
}

Until now I thought I don't have to call the release() method of a unique_ptr before leaving the scope (return from function) because the content of the unique_ptr will automatically be deleted if the unique_ptr runs out of scope. But if don't call the release() method I get the following error (VS 2010):

enter image description here

I think this error message occurs because the memory isn't correctly freed? What's the recommended approach dealing with unique_ptr, which is passed as an argument?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

很酷又爱笑 2024-12-30 08:38:34

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

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,则不需要智能指针,如果使用,那么您可能应该使用智能指针来使代码更加健壮。

Based on your description and comment I believe this is more what you are looking for:

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

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

  return result;
}

This string object is a STL container of wchar_t that has various helpful methods. One of which is c_str() which returns a c-style const wchar_t* version of the string contents for backwards compatibility with older code. Your DoWork function may be such a function that requires a c-style string so the above will work for you.


Now onto smart pointers 101:

In C++11 std::unique_ptr can be used to automatically destruct objects allocated on the heap freeing from the worries of exception unsafe code and manual memory management which can lead to memory leaks and other bad things. Say you had the following code:

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

Obviously that's a memory leak as once the scope of LeakyFunction ends we've lost the pointer on the stack and no longer can delete what it was pointing to on the heap. So we write this:

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

That's well and dandy unless you have an early return or throw an exception during the do stuff portion of code which puts you back to the same problem as before. So people started writing custom smart pointer classes which owned raw memory allocation by allocating on construction and deallocating on destruction. This concept has now become standard via things like std::unique_ptr so we can do the following:

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

In this way no matter when the scope of the function ends you don't have to worry things will be cleaned up properly. In short if you aren't using new you don't need a smart pointer and if you are then you probably should use a smart pointer to make your code more robust.

梓梦 2024-12-30 08:38:34

通过unique_ptr,您尝试在指向字符串常量的指针上调用delete

您必须只允许在指向使用 new 创建的对象的指针上调用 delete

Via unique_ptr, you are attempting to call delete on a pointer to a string literal constant.

You must only allow delete to be called on pointers that point to objects created using new.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文