I am puzzled with the following piece of code where I am trying to understand the difference between getter/setter of the C++ bracket operator.
#include <iostream>
using namespace std;
template <class T, std::size_t N>
class Buffer
{
public:
Buffer() : _pos(0) {}
~Buffer() {}
//T& operator[](std::size_t pos) { cout << "\nSet\n"; return _data[pos]; }
const T& operator[](std::size_t pos) const { cout << "\nGet\n"; return _data[pos]; }
private:
T _data[N];
std::size_t _pos;
};
int main()
{
Buffer<int, 10> b;
int i = b[0];
(void)i;
return 0;
}
I am compiling it using GCC 4.9.3 (MinGW). When I run it, it prints "Get" as expected, since I am not changing the Buffer object in the assignment
int i = b[0];But if I un-comment the setter operator
T& operator[](std::size_t pos)then this time the program prints "Set". I cannot explain this behavior.
I have read many examples, including this one, where it is recommended to use a 'proxy' class, but then I do not understand why this approach is not used in the implementation of std::array like in the GCC implementation. My Buffer class is intended to be similar to std::array.
What am I doing wrong?