C++ 中的 RAII 和智能指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/395123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:06:48  来源:igfitidea点击:

RAII and smart pointers in C++

c++smart-pointersraii

提问by Rob Kam

In practice with C++, what is RAII, what are smart pointers, how are these implemented in a program and what are the benefits of using RAII with smart pointers?

在 C++ 的实践中,什么是RAII,什么是智能指针,这些是如何在程序中实现的,以及将 RAII 与智能指针一起使用有什么好处?

回答by Michael Williamson

A simple (and perhaps overused) example of RAII is a File class. Without RAII, the code might look something like this:

RAII 的一个简单(可能是过度使用)示例是 File 类。如果没有 RAII,代码可能如下所示:

File file("/path/to/file");
// Do stuff with file
file.close();

In other words, we must make sure that we close the file once we've finished with it. This has two drawbacks - firstly, wherever we use File, we will have to called File::close() - if we forget to do this, we're holding onto the file longer than we need to. The second problem is what if an exception is thrown before we close the file?

换句话说,我们必须确保在完成文件后将其关闭。这有两个缺点 - 首先,无论我们在哪里使用 File,我们都必须调用 File::close() - 如果我们忘记这样做,我们会比需要的时间更长地保留文件。第二个问题是如果在我们关闭文件之前抛出异常怎么办?

Java solves the second problem using a finally clause:

Java 使用 finally 子句解决第二个问题:

try {
    File file = new File("/path/to/file");
    // Do stuff with file
} finally {
    file.close();
}

or since Java 7, a try-with-resource statement:

或者从 Java 7 开始,一个 try-with-resource 语句:

try (File file = new File("/path/to/file")) {
   // Do stuff with file
}

C++ solves both problems using RAII - that is, closing the file in the destructor of File. So long as the File object is destroyed at the right time (which it should be anyway), closing the file is taken care of for us. So, our code now looks something like:

C++ 使用 RAII 解决了这两个问题——即在 File 的析构函数中关闭文件。只要 File 对象在正确的时间被销毁(无论如何它应该是),关闭文件就会为我们处理。所以,我们的代码现在看起来像:

File file("/path/to/file");
// Do stuff with file
// No need to close it - destructor will do that for us

This cannot be done in Java since there's no guarantee when the object will be destroyed, so we cannot guarantee when a resource such as file will be freed.

这不能在 Java 中完成,因为无法保证对象何时会被销毁,因此我们无法保证文件等资源何时会被释放。

Onto smart pointers - a lot of the time, we just create objects on the stack. For instance (and stealing an example from another answer):

关于智能指针 - 很多时候,我们只是在堆栈上创建对象。例如(并从另一个答案中窃取一个例子):

void foo() {
    std::string str;
    // Do cool things to or using str
}

This works fine - but what if we want to return str? We could write this:

这很好用 - 但是如果我们想返回 str 怎么办?我们可以这样写:

std::string foo() {
    std::string str;
    // Do cool things to or using str
    return str;
}

So, what's wrong with that? Well, the return type is std::string - so it means we're returning by value. This means that we copy str and actually return the copy. This can be expensive, and we might want to avoid the cost of copying it. Therefore, we might come up with idea of returning by reference or by pointer.

那么,这有什么问题呢?好吧,返回类型是 std::string - 所以这意味着我们是按值返回的。这意味着我们复制 str 并实际返回副本。这可能很昂贵,我们可能希望避免复制它的成本。因此,我们可能会想到通过引用或指针返回的想法。

std::string* foo() {
    std::string str;
    // Do cool things to or using str
    return &str;
}

Unfortunately, this code doesn't work. We're returning a pointer to str - but str was created on the stack, so we be deleted once we exit foo(). In other words, by the time the caller gets the pointer, it's useless (and arguably worse than useless since using it could cause all sorts of funky errors)

不幸的是,此代码不起作用。我们正在返回一个指向 str 的指针 - 但是 str 是在堆栈上创建的,因此一旦我们退出 foo(),我们就会被删除。换句话说,当调用者获得指针时,它已经没用了(可以说比没用更糟糕,因为使用它可能会导致各种奇怪的错误)

So, what's the solution? We could create str on the heap using new - that way, when foo() is completed, str won't be destroyed.

那么,有什么解决办法呢?我们可以使用 new 在堆上创建 str - 这样,当 foo() 完成时, str 不会被销毁。

std::string* foo() {
    std::string* str = new std::string();
    // Do cool things to or using str
    return str;
}

Of course, this solution isn't perfect either. The reason is that we've created str, but we never delete it. This might not be a problem in a very small program, but in general, we want to make sure we delete it. We could just say that the caller must delete the object once he's finished with it. The downside is that the caller has to manage memory, which adds extra complexity, and might get it wrong, leading to a memory leak i.e. not deleting object even though it is no longer required.

当然,这个解决方案也不是完美的。原因是我们创建了str,但我们从来没有删除它。这在非常小的程序中可能不是问题,但一般来说,我们希望确保将其删除。我们可以说调用者一旦完成它就必须删除它。缺点是调用者必须管理内存,这增加了额外的复杂性,并且可能会出错,导致内存泄漏,即即使不再需要对象也不删除。

This is where smart pointers come in. The following example uses shared_ptr - I suggest you look at the different types of smart pointers to learn what you actually want to use.

这就是智能指针的用武之地。以下示例使用 shared_ptr - 我建议您查看不同类型的智能指针以了解您实际想要使用的内容。

shared_ptr<std::string> foo() {
    shared_ptr<std::string> str = new std::string();
    // Do cool things to or using str
    return str;
}

Now, shared_ptr will count the number of references to str. For instance

现在,shared_ptr 将计算对 str 的引用次数。例如

shared_ptr<std::string> str = foo();
shared_ptr<std::string> str2 = str;

Now there are two references to the same string. Once there are no remaining references to str, it will be deleted. As such, you no longer have to worry about deleting it yourself.

现在有两个对同一个字符串的引用。一旦没有剩余对 str 的引用,它将被删除。因此,您不再需要担心自己删除它。

Quick edit: as some of the comments have pointed out, this example isn't perfect for (at least!) two reasons. Firstly, due to the implementation of strings, copying a string tends to be inexpensive. Secondly, due to what's known as named return value optimisation, returning by value may not be expensive since the compiler can do some cleverness to speed things up.

快速编辑:正如一些评论指出的那样,这个例子并不完美(至少!)有两个原因。首先,由于字符串的实现,复制字符串的成本往往较低。其次,由于所谓的命名返回值优化,按值返回可能并不昂贵,因为编译器可以做一些聪明的事情来加快速度。

So, let's try a different example using our File class.

因此,让我们使用 File 类尝试不同的示例。

Let's say we want to use a file as a log. This means we want to open our file in append only mode:

假设我们想使用一个文件作为日志。这意味着我们要以仅附加模式打开我们的文件:

File file("/path/to/file", File::append);
// The exact semantics of this aren't really important,
// just that we've got a file to be used as a log

Now, let's set our file as the log for a couple of other objects:

现在,让我们将文件设置为其他几个对象的日志:

void setLog(const Foo & foo, const Bar & bar) {
    File file("/path/to/file", File::append);
    foo.setLogFile(file);
    bar.setLogFile(file);
}

Unfortunately, this example ends horribly - file will be closed as soon as this method ends, meaning that foo and bar now have an invalid log file. We could construct file on the heap, and pass a pointer to file to both foo and bar:

不幸的是,这个例子的结尾很糟糕——只要这个方法结束,文件就会被关闭,这意味着 foo 和 bar 现在有一个无效的日志文件。我们可以在堆上构造文件,并将指向文件的指针传递给 foo 和 bar:

void setLog(const Foo & foo, const Bar & bar) {
    File* file = new File("/path/to/file", File::append);
    foo.setLogFile(file);
    bar.setLogFile(file);
}

But then who is responsible for deleting file? If neither delete file, then we have both a memory and resource leak. We don't know whether foo or bar will finish with the file first, so we can't expect either to delete the file themselves. For instance, if foo deletes the file before bar has finished with it, bar now has an invalid pointer.

但是谁负责删除文件?如果既不删除文件,又存在内存和资源泄漏。我们不知道 foo 还是 bar 会先完成文件,所以我们不能指望它们自己删除文件。例如,如果 foo 在 bar 完成之前删除文件, bar 现在有一个无效的指针。

So, as you may have guessed, we could use smart pointers to help us out.

因此,正如您可能已经猜到的,我们可以使用智能指针来帮助我们解决问题。

void setLog(const Foo & foo, const Bar & bar) {
    shared_ptr<File> file = new File("/path/to/file", File::append);
    foo.setLogFile(file);
    bar.setLogFile(file);
}

Now, nobody needs to worry about deleting file - once both foo and bar have finished and no longer have any references to file (probably due to foo and bar being destroyed), file will automatically be deleted.

现在,没有人需要担心删除文件 - 一旦 foo 和 bar 都完成并且不再有任何对文件的引用(可能是由于 foo 和 bar 被破坏),文件将自动被删除。

回答by Johannes Schaub - litb

RAIIThis is a strange name for a simple but awesome concept. Better is the name Scope Bound Resource Management(SBRM). The idea is that often you happen to allocate resources at the begin of a block, and need to release it at the exit of a block. Exiting the block can happen by normal flow control, jumping out of it, and even by an exception. To cover all these cases, the code becomes more complicated and redundant.

RAII这是一个简单但很棒的概念的奇怪名称。更好的是名称范围绑定资源管理(SBRM)。这个想法是你经常碰巧在一个块的开始分配资源,并需要在一个块的出口释放它。退出块可以通过正常的流控制、跳出它甚至异常来发生。为了涵盖所有这些情况,代码变得更加复杂和冗余。

Just an example doing it without SBRM:

只是一个没有 SBRM 的例子:

void o_really() {
     resource * r = allocate_resource();
     try {
         // something, which could throw. ...
     } catch(...) {
         deallocate_resource(r);
         throw;
     }
     if(...) { return; } // oops, forgot to deallocate
     deallocate_resource(r);
}

As you see there are many ways we can get pwned. The idea is that we encapsulate the resource management into a class. Initialization of its object acquires the resource ("Resource Acquisition Is Initialization"). At the time we exit the block (block scope), the resource is freed again.

如您所见,我们可以通过多种方式获得成功。这个想法是我们将资源管理封装到一个类中。其对象的初始化获取资源(“Resource Acquisition Is Initialization”)。当我们退出块(块范围)时,资源再次被释放。

struct resource_holder {
    resource_holder() {
        r = allocate_resource();
    }
    ~resource_holder() {
        deallocate_resource(r);
    }
    resource * r;
};

void o_really() {
     resource_holder r;
     // something, which could throw. ...
     if(...) { return; }
}

That is nice if you have got classes of their own which are not solely for the purpose of allocating/deallocating resources. Allocation would just be an additional concern to get their job done. But as soon as you just want to allocate/deallocate resources, the above becomes unhandy. You have to write a wrapping class for every sort of resource you acquire. To ease that, smart pointers allow you to automate that process:

如果您有自己的类,而这些类不仅仅用于分配/取消分配资源,那就太好了。分配只是完成工作的另一个问题。但是,只要您只想分配/取消分配资源,上述操作就会变得不方便。您必须为获得的每种资源编写一个包装类。为了缓解这种情况,智能指针允许您自动执行该过程:

shared_ptr<Entry> create_entry(Parameters p) {
    shared_ptr<Entry> e(Entry::createEntry(p), &Entry::freeEntry);
    return e;
}

Normally, smart pointers are thin wrappers around new / delete that just happen to call deletewhen the resource they own goes out of scope. Some smart pointers, like shared_ptr allow you to tell them a so-called deleter, which is used instead of delete. That allows you, for instance, to manage window handles, regular expression resources and other arbitrary stuff, as long as you tell shared_ptr about the right deleter.

通常,智能指针是 new/delete 的薄包装器,delete当它们拥有的资源超出范围时恰好调用。一些智能指针,比如 shared_ptr 允许你告诉他们一个所谓的删除器,它用来代替delete. 例如,这允许您管理窗口句柄、正则表达式资源和其他任意内容,只要您告诉 shared_ptr 正确的删除器。

There are different smart pointers for different purposes:

有不同的智能指针用于不同的目的:

unique_ptr

unique_ptr

是一个专门拥有一个对象的智能指针。它不在 boost 中,但它可能会出现在下一个 C++ 标准中。它是non-copyable不可复制但支持transfer-of-ownership所有权转让。一些示例代码(下一个 C++):

Code:

代码:

unique_ptr<plot_src> p(new plot_src); // now, p owns
unique_ptr<plot_src> u(move(p)); // now, u owns, p owns nothing.
unique_ptr<plot_src> v(u); // error, trying to copy u

vector<unique_ptr<plot_src>> pv; 
pv.emplace_back(new plot_src); 
pv.emplace_back(new plot_src);

Unlike auto_ptr, unique_ptr can be put into a container, because containers will be able to hold non-copyable (but movable) types, like streams and unique_ptr too.

与 auto_ptr 不同,unique_ptr 可以放入容器中,因为容器将能够保存不可复制(但可移动)的类型,例如流和 unique_ptr。

scoped_ptr

scoped_ptr

是一个既不可复制也不可移动的 boost 智能指针。当您想确保在超出范围时删除指针时,这是一个完美的选择。

Code:

代码:

void do_something() {
    scoped_ptr<pipe> sp(new pipe);
    // do something here...
} // when going out of scope, sp will delete the pointer automatically. 

shared_ptr

shared_ptr

用于共享所有权。因此,它既可复制又可移动。多个智能指针实例可以拥有相同的资源。一旦拥有该资源的最后一个智能指针超出范围,该资源将被释放。我的一个项目的一些真实世界示例:

Code:

代码:

shared_ptr<plot_src> p(new plot_src(&fx));
plot1->add(p)->setColor("#00FF00");
plot2->add(p)->setColor("#FF0000");
// if p now goes out of scope, the src won't be freed, as both plot1 and 
// plot2 both still have references. 

As you see, the plot-source (function fx) is shared, but each one has a separate entry, on which we set the color. There is a weak_ptr class which is used when code needs to refer to the resource owned by a smart pointer, but doesn't need to own the resource. Instead of passing a raw pointer, you should then create a weak_ptr. It will throw an exception when it notices you try to access the resource by an weak_ptr access path, even though there is no shared_ptr anymore owning the resource.

如您所见,绘图源(函数 fx)是共享的,但每个都有一个单独的条目,我们在其上设置颜色。当代码需要引用智能指针拥有的资源但不需要拥有该资源时,会使用一个 weak_ptr 类。然后你应该创建一个weak_ptr,而不是传递一个原始指针。当它注意到您尝试通过weak_ptr 访问路径访问资源时,它会抛出异常,即使不再拥有该资源的shared_ptr。

回答by Drew Dormann

The premise and reasons are simple, in concept.

从概念上讲,前提和原因很简单。

RAII is the design paradigm to ensure that variables handle all needed initialization in their constructors and all needed cleanup in their destructors.This reduces all initialization and cleanup to a single step.

RAII 是确保变量在其构造函数中处理所有需要的初始化以及在其析构函数中处理所有需要的清理的设计范式这将所有初始化和清理减少到一个步骤。

C++ does not require RAII, but it is increasingly accepted that using RAII methods will produce more robust code.

C++ 不需要 RAII,但越来越多的人认为使用 RAII 方法将产生更健壮的代码。

The reason that RAII is useful in C++ is that C++ intrinsically manages the creation and destruction of variables as they enter and leave scope, whether through normal code flow or through stack unwinding triggered by an exception. That's a freebie in C++.

RAII 在 C++ 中有用的原因是 C++ 在变量进入和离开作用域时本质上管理变量的创建和销毁,无论是通过正常的代码流还是通过由异常触发的堆栈展开。这是 C++ 中的免费赠品。

By tying all initialization and cleanup to these mechanisms, you are ensured that C++ will take care of this work for you as well.

通过将所有初始化和清理与这些机制联系起来,您可以确保 C++ 也会为您处理这项工作。

Talking about RAII in C++ usually leads to the discussion of smart pointers, because pointers are particularly fragile when it comes to cleanup. When managing heap-allocated memory acquired from malloc or new, it is usually the responsibility of the programmer to free or delete that memory before the pointer is destroyed. Smart pointers will use the RAII philosophy to ensure that heap allocated objects are destroyed any time the pointer variable is destroyed.

在 C++ 中谈论 RAII 通常会导致对智能指针的讨论,因为在清理时指针特别脆弱。在管理从 malloc 或 new 获取的堆分配内存时,程序员通常有责任在指针被销毁之前释放或删除该内存。智能指针将使用 RAII 原理来确保在销毁指针变量时销毁堆分配的对象。

回答by mannicken

Smart pointer is a variation of RAII. RAII means resource acquisition is initialization. Smart pointer acquires a resource (memory) before usage and then throws it away automatically in a destructor. Two things happen:

智能指针是 RAII 的一种变体。RAII 表示资源获取是初始化。智能指针在使用前获取资源(内存),然后在析构函数中自动将其丢弃。发生两件事:

  1. We allocate memorybefore we use it, always, even when we don't feel like it -- it's hard to do another way with a smart pointer. If this wasn't happening you will try to access NULL memory, resulting in a crash (very painful).
  2. We free memoryeven when there's an error. No memory is left hanging.
  1. 我们总是在使用之前分配内存,即使我们不喜欢它 - 用智能指针很难做另一种方式。如果没有发生这种情况,您将尝试访问 NULL 内存,从而导致崩溃(非常痛苦)。
  2. 即使出现错误,我们也会释放内存。没有任何记忆是悬而未决的。

For instance, another example is network socket RAII. In this case:

例如,另一个例子是网络套接字 RAII。在这种情况下:

  1. We open network socketbefore we use it,always, even when we don't feel like -- it's hard to do it another way with RAII. If you try doing this without RAII you might open empty socket for, say MSN connection. Then message like "lets do it tonight" might not get transferred, users will not get laid, and you might risk getting fired.
  2. We close network socketeven when there's an error. No socket is left hanging as this might prevent the response message "sure ill be on bottom" from hitting sender back.
  1. 我们在使用网络套接字之前总是打开它,即使我们不觉得——很难用 RAII 以另一种方式做到这一点。如果您尝试在没有 RAII 的情况下执行此操作,您可能会打开空套接字,例如 MSN 连接。然后像“让我们今晚做吧”之类的消息可能不会被转移,用户不会被骗,你可能会冒被解雇的风险。
  2. 即使出现错误,我们也会关闭网络套接字。没有套接字被挂起,因为这可能会阻止响应消息“肯定会在底部”击中发件人。

Now, as you can see, RAII is a very useful tool in most cases as it helps people to get laid.

现在,正如您所看到的,RAII 在大多数情况下是一个非常有用的工具,因为它可以帮助人们上床。

C++ sources of smart pointers are in millions around the net including responses above me.

网络上的 C++ 智能指针源数以百万计,包括我上面的响应。

回答by Jason S

Boost has a number of these including the ones in Boost.Interprocessfor shared memory. It greatly simplifies memory management, especially in headache-inducing situations like when you have 5 processes sharing the same data structure: when everyone's done with a chunk of memory, you want it to automatically get freed & not have to sit there trying to figure out who should be responsible for calling deleteon a chunk of memory, lest you end up with a memory leak, or a pointer which is mistakenly freed twice and may corrupt the whole heap.

Boost 有许多这些,包括Boost.Interprocess 中用于共享内存的那些。它极大地简化了内存管理,尤其是在令人头疼的情况下,例如当您有 5 个进程共享相同的数据结构时:当每个人都使用完一块内存时,您希望它自动被释放而不必坐在那里试图弄清楚谁应该负责调用delete一块内存,以免最终导致内存泄漏,或者错误地释放两次并可能损坏整个堆的指针。

回答by Jason S

void foo()
{
   std::string bar;
   //
   // more code here
   //
}

No matter what happens, bar is going to be properly deleted once the scope of the foo() function has been left behind.

无论发生什么,一旦 foo() 函数的作用域被抛在后面, bar 就会被正确删除。

Internally std::string implementations often use reference counted pointers. So the internal string only needs to be copied when one of the copies of the strings changed. Therefore a reference counted smart pointer makes it possible to only copy something when necessary.

内部 std::string 实现通常使用引用计数指针。因此,只有在字符串的副本之一发生更改时才需要复制内部字符串。因此,引用计数智能指针可以仅在必要时复制某些内容。

In addition, the internal reference counting makes it possible that the memory will be properly deleted when the copy of the internal string is no longer needed.

此外,内部引用计数使得当不再需要内部字符串的副本时,内存将被正确删除。