Search code examples
c++arraysoverloadingshared-ptrc++17

C++17 std::shared_ptr<> overload operator[] for array-like objects


I have a base class that include array and provide a simple operator[] :

class Object
{
public:
    std::shared_ptr<Object> operator[](const int index);

    [...]

private:
    std::vector<std::shared_ptr<Object>> internal_array;
};

When I want to get a direct access to the operator[] (since C++17) without dereference, my compiler (MSVC 2017) dont like that :

std::shared_ptr<Object> one_object;
std::shared_ptr<Object> another_object = one_object[0];

If a array-type (say std::vector) is allowed for direct index array access, why an class with operator[] is not?


Solution

  • C++17 shared_ptr<T>::operator[] is well defined only for array types, std::vector is not an array type (say, int[],int[3],etc.. are). That said, the relevant standard doc reads:

    [util.smartptr.shared.obs] element_type& operator[](ptrdiff_t i) const[...]Remarks: When T is not an array type, it is unspecified whether this member function is declared. If it is declared, it is unspecified what its return type is, except that the declaration (although not necessarily the definition) of the function shall be well formed.

    this means that an implementation may provide a member subscript operator even for non-array types, the only requirement being its declaration to be well formed (this is in order to be SFINAE friendly); it's definition may or may not be well-formed, and may or may not do the 'right' thing.