RAII和C ++中的智能指针 [英] RAII and smart pointers in C++

查看:130
本文介绍了RAII和C ++中的智能指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

RAII的一个简单(也许过度使用)的例子是一个File类。没有RAII,代码可能看起来像这样:

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

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

换句话说,我们必须确保在我们完成后关闭文件。这有两个缺点 - 首先,无论我们使用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?

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

Java solves the second problem using a finally clause:

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

C ++使用RAII解决了这两个问题 - 文件。只要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:

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

在Java中无法做到的原因是,我们无法保证对象何时被销毁,因此无法保证资源(如文件)何时被释放。

The reason this cannot be done in Java is that we have no guarantee over when the object will be destroyed, so cannot guarantee when a resource such as file will be freed.

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

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
}

- 但是如果我们要返回str呢?我们可以这样写:

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

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

那么,有什么问题?嗯,返回类型是std :: string - 所以这意味着我们返回值。这意味着我们复制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* foo() {
    std::string str;
    // Do cool things to or using str
    return &str;
}

不幸的是,这个代码不工作。我们返回一个指向str的指针 - 但str是在堆栈上创建的,所以我们在退出foo()时被删除。换句话说,在调用者获取指针的时候,它是无用的(并且可以说是比无用的,因为使用它可能会导致各种各样的错误)

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)

解决方案?我们可以使用new在堆上创建str - 这样,当foo()完成时,str不会被销毁。

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.

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

当然,这个解决方案也不完美。原因是我们创建了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.

这是智能指针进来的地方。下面的例子使用shared_ptr - 我建议你看看不同类型的智能指针,了解你实际想要使用的东西。

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<std::string> foo() {
    shared_ptr<std::string> str = new std::string();
    // Do cool things to or using str
    return str;
}



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

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

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

现在有两个引用指向同一个字符串。一旦没有对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.

快速编辑:正如一些评论指出的,此示例不适用于最少!)两个原因。首先,由于字符串的实现,复制字符串往往是便宜的。其次,由于所谓的命名返回值优化,通过值返回可能不昂贵,因为编译器可以做一些聪明以加快速度。

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.

因此,让我们试试一个不同的例子使用我们的File类。

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

假设我们要使用一个文件作为日志。这意味着我们要以append only模式打开文件:

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

不幸的是,这个例子结束可怕 - 文件将被关闭,结束,意味着foo和bar现在有一个无效的日志文件。我们可以在堆上构建文件,并传递一个指向文件的指针到foo和bar:

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:

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

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

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.

所以,你可能已经猜到了,我们可以使用智能指针以帮助我们。

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

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

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.

这篇关于RAII和C ++中的智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆