简体   繁体   中英

unique_ptr<T,Deleter> constructor requires that Deleter is nothrow

unique_ptr (constructor) @ cppreference

unique_ptr( pointer p, /* see below */ d1 ) noexcept;
(3) 
unique_ptr( pointer p, /* see below */ d2 ) noexcept;
(4)

Here are 2 constructors and the description for the case Deleter is non-reference

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)

I checked both gcc and llvm code but I don't see nothrow requirement is enforced. Constructors 3-4 are marked noexcept so it makes sense that the Deleter should not throw when its constructors are called. But I'm not sure why in the example they provided the constructors are not marked as 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.

It's not enforced - directly.
Here's the actual words from the standard :

For the first constructor, if D is not a reference type, D shall meet the Cpp17CopyConstructible requirements and such construction shall not exit via an exception. For the second constructor, if D is not a reference type, D shall meet the Cpp17MoveConstructible requirements and such construction shall not exit via an exception.

What that says is that if your copy/move constructor exits via an exception, you have undefined behavior. [ 'shall' in this case is a requirement on the user. ]

If you're lucky, then the program will call terminate with a nice message. However, you have no guarantees.

(Later) Note: The requirement is NOT that they be noexcept , but rather that they do not exit via an exception. That's why the examples on cppreference are fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM