将emplace_back与unique_ptrs容器一起使用是否安全? [英] Is it safe to use emplace_back with a container of unique_ptrs?

查看:135
本文介绍了将emplace_back与unique_ptrs容器一起使用是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

std::vector<std::unique_ptr<int>> ptrsToInts;
ptrsToInts.emplace_back(new int);

如果向量中发生了重新分配,但失败了(抛出std::bad_alloc),我是安全的"还是泄漏int?

If reallocation occurs in the vector, and that fails (throwing std::bad_alloc), am I "safe" or will I leak an int?

C ++ 11 23.3.6.5 [vector.modifiers]/1说:

C++11 23.3.6.5 [vector.modifiers]/1 says:

如果不是复制构造函数,移动构造函数,赋值运算符或T的移动赋值运算符或任何InputIterator操作抛出异常,则没有任何效果.

If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects.

似乎表明这是一个潜在问题.也就是说,如果没有效果",那么就不会构造unique_ptr,因此析构函数的行为将依赖于delete不会发生指针. (这可能表明emplace_back的容器应禁止使用emplace_back)

which seems to indicate that this is a potential problem. That is, if there are "no effects", then no unique_ptr ever was constructed, and therefore the destructor behavior one would rely on to delete that pointer would not occur. (Which might indicate that emplace_back should be banned for containers of unique_ptrs)

推荐答案

如果需要重新分配并且失败,那么是的,您的对象永远不会进入容器,因此会丢失.

If reallocation is required and it fails, then yes, your object never went into the container and will thus be lost.

但是,应注意,这是纯用户错误.对于unique_ptr的容器,不应禁止" emplace_back,因为这样做有非常安全的方式(例如,事先reserve留出空间,因此您知道它将一直存在).另外,您可以传入整个unique_ptr,因为它完全可以使用move构造函数.

However, it should be noted that this is pure user error. emplace_back should not be "banned" for containers of unique_ptr, because there are perfectly safe ways of doing this (such as reserveing the space beforehand, so you know it will always be there). Also, you can pass in whole unique_ptrs, since it's perfectly capable of using a move constructor.

所以,确实,在抛出异常之前,没有正确地将非RAII对象(int*)包装在RAII对象中是您的错.

So really, it's your fault for not properly wrapping your non-RAII object (the int*) in a RAII object before the point where you could throw exceptions.

这篇关于将emplace_back与unique_ptrs容器一起使用是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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