Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 833
Nikos C. Avatar asked Mar 28 '16 22:03

Nikos C.


1 Answers

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.

like image 122
Nicol Bolas Avatar answered Sep 30 '22 19:09

Nicol Bolas