This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Why does the [] operator in vector behave as it does?


Hi Luke,

Your "A" class is violating the requirements of what can be used with a
std::vector, since it is not really assignable.  The compiler is generating
an implicit synthetic assignment operator, which does not do the necessary
memory management for your non-trivial class's id data member.

Add this routine:

  A& operator = (A const& rhs)
  {
    int* temp = new int(rhs.GetValue());
    std::swap(id, temp);
    delete temp;
    return *this;
  }

And this, to avoid the *(rhs.id) syntax, make the code self-documenting, and
test for the NULL id case:

  int GetValue() const
  {
    assert(id != NULL);
    return *id;
  }

HTH,
--Eljay


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]