Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

arithmetic of pointers in c++ due to allocation

Tags:

c++

pointers

math

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?

like image 533
mvxxx Avatar asked Dec 23 '22 07:12

mvxxx


1 Answers

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.

like image 143
StoryTeller - Unslander Monica Avatar answered Dec 28 '22 08:12

StoryTeller - Unslander Monica