[英]How to combine std::make_shared and new(std::nothrow)
C++'s new has an option to return a null pointer instead of throwing a bad_alloc exception when an allocation failed. C ++的new有一个选项可以返回空指针,而不是在分配失败时抛出bad_alloc异常。
Foo * pf = new(std::nothrow) Foo(1, 2, 3);
(Yes, I understand this only prevents the new from throwing a bad_alloc; it doesn't prevent Foo's constructor from throwing an exception.) (是的,我理解这只会阻止new抛出bad_alloc;它不会阻止Foo的构造函数抛出异常。)
If you want to use a shared pointer instead of a raw pointer, you generally should use make_shared, as it gets clever about the allocation of the control block. 如果你想使用共享指针而不是原始指针,你通常应该使用make_shared,因为它对控制块的分配很聪明。
auto pf = std::make_shared<Foo>(1, 2, 3);
make_shared encapsulates the new, which makes it impossible(?) to choose the nothrow version. make_shared封装了new,这使得(?)无法选择nothrow版本。 So it seems you have to abandon make_shared and call new explicitly. 因此,您似乎必须放弃make_shared并明确调用new。
std::shared_ptr<Foo> pf(new(std::nothrow) Foo(1, 2, 3));
This eliminates the optimization of allocating the control block with the Foo, and the control block allocation could fail independently of the Foo allocation, but I don't want to focus on that. 这消除了使用Foo分配控制块的优化,并且控制块分配可能独立于Foo分配而失败,但我不想关注它。 Let's assume the control block is small so its allocation will never fail in practice. 让我们假设控制块很小,所以它的分配在实践中永远不会失败。 It's the failure to allocate space for the Foo that concerns me. 这是为我担心的Foo分配空间的失败。
Is there a way to get the single-allocation advantage of make_shared while retaining the ability to simply get a null pointer instead of a bad_alloc exception when allocating space for the Foo? 有没有办法获得make_shared的单一分配优势,同时保留在为Foo分配空间时简单地获取空指针而不是bad_alloc异常的能力?
它看起来像allocate_shared
,传入一个使用nothrow
new的分配器应该为你做的伎俩。
Just have a custom nake_foo and catch the exception: 只需要一个自定义的nake_foo并捕获异常:
#include <memory>
struct Foo {
Foo(int, int, int) { throw std::bad_alloc(); }
};
std::shared_ptr<Foo> make_foo(int a, int b, int c) {
try { return std::make_shared<Foo>(a, b, c); }
catch (const std::bad_alloc&) { return std::shared_ptr<Foo>(); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.