在 C++ 中使用指向动态分配对象的指针向量时如何

How to avoid memory leaks when using a vector of pointers to dynamically allocated objects in C++?(在 C++ 中使用指向动态分配对象的指针向量时如何避免内存泄漏?)

本文介绍了在 C++ 中使用指向动态分配对象的指针向量时如何避免内存泄漏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用指向对象的指针向量.这些对象是从一个基类派生出来的,并被动态分配和存储.

I'm using a vector of pointers to objects. These objects are derived from a base class, and are being dynamically allocated and stored.

例如,我有类似的东西:

For example, I have something like:

vector<Enemy*> Enemies;

我将从 Enemy 类派生,然后为派生类动态分配内存,如下所示:

and I'll be deriving from the Enemy class and then dynamically allocating memory for the derived class, like this:

enemies.push_back(new Monster());

为了避免内存泄漏和其他问题,我需要注意哪些事项?

What are things I need to be aware of to avoid memory leaks and other problems?

推荐答案

std::vector 会像往常一样为你管理内存,但这个内存将是指针,而不是对象.

std::vector will manage the memory for you, like always, but this memory will be of pointers, not objects.

这意味着一旦您的向量超出范围,您的类将在内存中丢失.例如:

What this means is that your classes will be lost in memory once your vector goes out of scope. For example:

#include <vector>

struct base
{
    virtual ~base() {}
};

struct derived : base {};

typedef std::vector<base*> container;

void foo()
{
    container c;

    for (unsigned i = 0; i < 100; ++i)
        c.push_back(new derived());

} // leaks here! frees the pointers, doesn't delete them (nor should it)

int main()
{
    foo();
}

您需要做的是确保在向量超出范围之前删除所有对象:

What you'd need to do is make sure you delete all the objects before the vector goes out of scope:

#include <algorithm>
#include <vector>

struct base
{
    virtual ~base() {}
};

struct derived : base {};

typedef std::vector<base*> container;

template <typename T>
void delete_pointed_to(T* const ptr)
{
    delete ptr;
}

void foo()
{
    container c;

    for (unsigned i = 0; i < 100; ++i)
        c.push_back(new derived());

    // free memory
    std::for_each(c.begin(), c.end(), delete_pointed_to<base>);
}

int main()
{
    foo();
}

但是,这很难维护,因为我们必须记住执行某些操作.更重要的是,如果在元素分配和释放循环之间发生异常,释放循环将永远不会运行,无论如何你都会被内存泄漏所困扰!这称为异常安全,这是需要自动完成解除分配的一个关键原因.

This is difficult to maintain, though, because we have to remember to perform some action. More importantly, if an exception were to occur in-between the allocation of elements and the deallocation loop, the deallocation loop would never run and you're stuck with the memory leak anyway! This is called exception safety and it's a critical reason why deallocation needs to be done automatically.

如果指针删除自己会更好.这些被称为智能指针,标准库提供了std::unique_ptrstd::shared_ptr.

Better would be if the pointers deleted themselves. Theses are called smart pointers, and the standard library provides std::unique_ptr and std::shared_ptr.

std::unique_ptr 表示指向某个资源的唯一(非共享、单一所有者)指针.这应该是您的默认智能指针,并且完全替代了任何原始指针的使用.

std::unique_ptr represents a unique (unshared, single-owner) pointer to some resource. This should be your default smart pointer, and overall complete replacement of any raw pointer use.

auto myresource = /*std::*/make_unique<derived>(); // won't leak, frees itself

std::make_unique 由于疏忽,C++11 标准中缺少

std::make_unique,但您可以自己制作.要直接创建一个 unique_ptr(如果可以的话,不推荐超过 make_unique),请执行以下操作:

std::make_unique is missing from the C++11 standard by oversight, but you can make one yourself. To directly create a unique_ptr (not recommended over make_unique if you can), do this:

std::unique_ptr<derived> myresource(new derived());

唯一指针只有移动语义;它们不能被复制:

Unique pointers have move semantics only; they cannot be copied:

auto x = myresource; // error, cannot copy
auto y = std::move(myresource); // okay, now myresource is empty

这就是我们在容器中使用它所需的全部内容:

And this is all we need to use it in a container:

#include <memory>
#include <vector>

struct base
{
    virtual ~base() {}
};

struct derived : base {};

typedef std::vector<std::unique_ptr<base>> container;

void foo()
{
    container c;

    for (unsigned i = 0; i < 100; ++i)
        c.push_back(make_unique<derived>());

} // all automatically freed here

int main()
{
    foo();
}

shared_ptr 具有引用计数复制语义;它允许多个所有者共享对象.它跟踪一个对象存在多少个 shared_ptr ,当最后一个不再存在时(该计数变为零),它释放指针.复制只是增加了引用计数(并且以更低的、几乎免费的成本转移所有权).您可以使用 std::make_shared(或直接如上所示,但由于 shared_ptr 必须在内部进行分配,因此使用它通常更有效且技术上更安全)make_shared).

shared_ptr has reference-counting copy semantics; it allows multiple owners sharing the object. It tracks how many shared_ptrs exist for an object, and when the last one ceases to exist (that count goes to zero), it frees the pointer. Copying simply increases the reference count (and moving transfers ownership at a lower, almost free cost). You make them with std::make_shared (or directly as shown above, but because shared_ptr has to internally make allocations, it's generally more efficient and technically more exception-safe to use make_shared).

#include <memory>
#include <vector>

struct base
{
    virtual ~base() {}
};

struct derived : base {};

typedef std::vector<std::shared_ptr<base>> container;

void foo()
{
    container c;

    for (unsigned i = 0; i < 100; ++i)
        c.push_back(std::make_shared<derived>());

} // all automatically freed here

int main()
{
    foo();
}

请记住,您通常希望使用 std::unique_ptr 作为默认值,因为它更轻量级.此外,std::shared_ptr 可以由 std::unique_ptr 构成(但反之则不然),所以可以从小处着手.

Remember, you generally want to use std::unique_ptr as a default because it's more lightweight. Additionally, std::shared_ptr can be constructed out of a std::unique_ptr (but not vice versa), so it's okay to start small.

或者,您可以使用创建的容器来存储指向对象的指针,例如 boost::ptr_container:

Alternatively, you could use a container created to store pointers to objects, such as a boost::ptr_container:

#include <boost/ptr_container/ptr_vector.hpp>

struct base
{
    virtual ~base() {}
};

struct derived : base {};

// hold pointers, specially
typedef boost::ptr_vector<base> container;

void foo()
{
    container c;

    for (int i = 0; i < 100; ++i)
        c.push_back(new Derived());

} // all automatically freed here

int main()
{
    foo();
}

虽然 boost::ptr_vector 在 C++03 中有明显的用途,但我现在不能说相关性,因为我们可以使用 std::vector 可能很少或没有可比的开销,但应该测试此声明.

While boost::ptr_vector<T> had obvious use in C++03, I can't speak of the relevance now because we can use std::vector<std::unique_ptr<T>> with probably little to no comparable overhead, but this claim should be tested.

无论如何,永远不要明确释放代码中的内容.总结一下以确保自动处理资源管理.您的代码中不应包含原始拥有指针.

Regardless, never explicitly free things in your code. Wrap things up to make sure resource management is dealt with automatically. You should have no raw owning pointers in your code.

作为游戏的默认设置,我可能会使用 std::vector>.无论如何,我们希望共享,它足够快,直到分析表明否则,它是安全的,并且易于使用.

As a default in a game, I would probably go with std::vector<std::shared_ptr<T>>. We expect sharing anyway, it's fast enough until profiling says otherwise, it's safe, and it's easy to use.

这篇关于在 C++ 中使用指向动态分配对象的指针向量时如何避免内存泄漏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 C++ 中使用指向动态分配对象的指针向量时如何

基础教程推荐