Home > Enterprise >  std::array's data member is public in a standard library implementation. Why?
std::array's data member is public in a standard library implementation. Why?

Time:08-02

I was trying to study standard library implementation of the containers that are part of the C standard library. I have Microsoft Visual Studio 2022 on my machine and I could go to the header file definition of std::array class.

While I reached the end of the class definition of std::array class, I noticed that the data member is not declared private and above it were all the public member functions, so that make the data member public as well.

So to test it, I tried to access it in my std::array object defined in main() and to my surprise I could access it and it printed the proper value in the output too!

#include <array>
#include <iostream>
int main() 
{
    std::array<int, 5> staticArray{0,1,2,3,4};
    std::cout << staticArray._Elems[1] << std::endl;
}

Is this allowed?! Anybody can corrupt the data, right?

CodePudding user response:

It is required that std::array have a public member to satisfy the requirement that std::array be an aggregate.

An array is an aggregate that can be list-initialized with up to N elements whose types are convertible to T.

https://eel.is/c draft/array#overview-2

It doesn't however specify what the public member should be named, since the only requirement is that it is an aggregate that can be list-initialized.

_Elems won't necessarily be compatible with other standard library implementations.

With respect to your concern of anyone being able to corrupt the data, anyone can already do that via any of the mutable accessors: data(), operator[], etc

CodePudding user response:

@mpark has got it exactly right. (Hi, Michael!)

template <typename T, size_t SZ>
struct Arr1 {
public:
    T elems[SZ];
};
    
template <typename T, size_t SZ>
struct Arr2 {
private:
    T elems[SZ];
};

int main () {
    static_assert (std::is_aggregate<Arr1<int, 4>>::value, ""); // OK
    static_assert (std::is_aggregate<Arr2<int, 4>>::value, ""); // fails
}
  • Related