unique_ptr (constructor) @ cppreference
unique_ptr( pointer p, /* see below */ d1 ) noexcept;
(3)
unique_ptr( pointer p, /* see below */ d2 ) noexcept;
(4)
这里有 2 个构造函数,Deleter 案例的描述非引用
a) If D is non-reference type A, then the signatures are:
unique_ptr(pointer p, const A& d) noexcept;
(1) (requires that Deleter is nothrow-CopyConstructible)
unique_ptr(pointer p, A&& d) noexcept;
(2) (requires that Deleter is nothrow-MoveConstructible)
我检查了 gcc 和 llvm 代码,但没有看到强制执行 nothrot
要求。构造函数 3-4 被标记为 noexcept
,因此在调用构造函数时,Deleter
不应抛出异常。但我不确定为什么在他们提供的示例中,构造函数没有标记为 noexcept
。
struct D { // deleter
D() {};
D(const D&) { std::cout << "D copy ctor\n"; }
D(D&) { std::cout << "D non-const copy ctor\n";}
D(D&&) { std::cout << "D move ctor \n"; }
void operator()(Foo* p) const {
std::cout << "D is deleting a Foo\n";
delete p;
};
};
最佳答案
I checked both gcc and llvm code but I don't see
nothrow
requirement is enforced.
它不是直接强制执行的。
这是actual words from the standard :
For the first constructor, if
D
is not a reference type,D
shall meet theCpp17CopyConstructible
requirements and such construction shall not exit via an exception. For the second constructor, ifD
is not a reference type,D
shall meet theCpp17MoveConstructible
requirements and such construction shall not exit via an exception.
这意味着,如果您的复制/移动构造函数通过异常退出,则会出现未定义的行为。 [在这种情况下,“应”是对用户的要求。 ]
如果幸运的话,程序将调用terminate
并带有一条友好的消息。但是,您没有任何保证。
(稍后)注意:要求不是它们是 noexcept
,而是它们不通过异常退出。这就是为什么 cppreference 上的示例很好。
关于c++ - unique_ptr<T,Deleter> 构造函数要求 Deleter 不抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603288/