简体   繁体   中英

Under which circumstances might std::unique_ptr::operator[] throw?

I have an operator[] for my class and all it does is call std::unique_ptr::operator[] on a unique_ptr member. The relevant part is just this:

template <typename T> struct Foo {
    T& operator [](const size_t pos) const noexcept
    {
        return data_[pos];
    }

    std::unique_ptr<T[]> data_;
};

I've marked the operator as noexcept . However, unique_ptr::operator[] is not noexcept . I am unable to find out why that is, and whether I can just assume that it will never throw. unique_ptr::operator[] itself does not list any exceptions in the documentation (cppreference and MSDN claim it does not define any list of exceptions it might throw.)

So I assume the missing noexcept might either be: a) a mistake, or b) the underlying datatype accessed by the operator might throw. Option a would be nice, since that would mean I can mark my own operator noexcept . Option b would be difficult to understand, since all the operator does it get a reference and it doesn't call anything.

So, long story short, is there any possibility of unique_ptr::operator[] ever throwing, and is it safe to call it from a noexcept function?

I thought I give it a try (I am not sure of the answer).

I went through the noexcept reference and my understanding is that noexcept is simply indicating that the function should not throw exception, so that the compiler could make more agressive optimisations. As to why the unique_ptr::operator[] is not noexcept I guess that the one standardising imagined that some implementors may throw and some other may not. My opinion is that unique_ptr::operator[] may be throwing depending on the implementation of unique_ptr (typically when the index is out of bound). However depending of the context of your code you could make sure this won't happen and decide to specify noexcept for your operator[].

So, long story short, is there any possibility of unique_ptr::operator[] ever throwing

Yes. It will simply use [] on the pointer type that it has. And that could throw. Recall that, thanks to deleter gymnastics, the pointer type need not be an actual pointer. It could be a user-defined object type with its own operator[] overload that could throw on out-of-bounds use.

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