I created a class which contains 3 elements of the same type (something like std::pair<T,std::pair<T,T>>
). Moreover I prepared it for use for(auto&var:t)
But I don't know if I did it safely.
template <class T>
class Troika
{
public:
Troika(const T& f, const T& s, const T& t)
:first(f), second(s), third(t) {}
Troika(){}
T first;
T second;
T third;
typedef T* iterator;
typedef const T* const_iterator;
iterator begin()
{
return &first;
}
const_iterator begin() const
{
return &first;
}
iterator end()
{
return &third+1;
}
const_iterator end() const
{
return &third + 1;
}
};
I mean about this part: return &third + 1;
. I know that if somebody have not huge knowledge about arithmetic of pointers in c++, it is really dangerous. Are these elements alocated one by one near each other?
Are these elements alocated one by one near each other?
They likely are, since they have the exact same accessibility. But it still doesn't make your implementation safe. Pointer arithmetic is only valid for elements in the same array object. Those three are not in the same array, there is no array in sight. Any attempt to use those iterators will result in undefined behavior.
I'm not sure of your intention in defining this class, but for a container of three elements of the same type, I'd offer the more idiomatic:
template<typename T>
using Troika = std::array<T, 3>;
You lose the first
, second
and third
named members, but gain indexing (which is as good I think) and iteration for free.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With