Under what circumstances can there be std :: unique_ptr :: operator [] throw?

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

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

I marked the operator as noexcept . However, unique_ptr::operator[] not noexcept . I can’t understand why this is so, and can I just assume that he will never quit. unique_ptr::operator[] itself does not list any exceptions in the documentation (cppreference and MSDN claim that it does not define a list of exceptions that it can throw.)

So, I assume that the missing noexcept may be: a) an error, or b) the underlying data type that the operator can access. Option a would be nice, as that would mean that I can mark my own noexcept . Option b will be hard to understand, since the whole operator gets the link and says nothing.

So, a long story, is it possible for unique_ptr::operator[] to ever be thrown, and is it safe to call from the noexcept function?

+6
source share
2 answers

So, a long story, is it possible to unique_repeat :: operator [] to ever throw

Yes. It will simply use [] according to the type of pointer it has. And it can quit. Recall that, thanks to deleter gymnastics, the type of pointer does not have to be the actual pointer. This can be a user-defined object type with its own operator[] overload, which can be used for use outside of the bounds.

+1
source

I thought I would try (I'm not sure about the answer).

I looked at the noexcept reference , and I understand that noexcept simply indicates that the function should not throw an exception, so that the compiler can do more aggressive optimizations. Regarding why unique_ptr::operator[] not noexcept , I assume that the standardization some developers suggest may drop and the other not. My opinion is that unique_ptr::operator[] can be unique_ptr depending on the implementation of unique_ptr (usually when the index is not connected). However, depending on the context of your code, you can make sure that this does not happen and decide to specify noexcept for your operator [].

+1
source

All Articles