0

I have the following:

class MyClass
{
  private:
    int my_data;
    MyClass* my_pointer;

  public:
    MyClass():
      my_data(0),
      my_pointer(this)
    {}

    MyClass(const int& data):
      my_data(data),
      my_pointer(this)
    {}
};

However, when I run

std::vector<MyClass> vec(10);
int n = {0};
std::generate(vec.begin(), vec.end(), [&n] { return MyClass(n++); });

each of my_pointer for the ten instances has the same value. How can I correct this code so that my_pointer points to the instance the field is in?

cm007
  • 1,352
  • 4
  • 20
  • 40
  • 2
    You need a copy constructor that updates `this` to point to the new object. – Barmar Mar 23 '17 at 02:18
  • 1
    You might want to see [this](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). – songyuanyao Mar 23 '17 at 02:19
  • 1
    What's happening is that each time through the loop it creates a local object in the function, then copies that into the vector. All the local objects are at the same stack address, because it just keeps pushing and popping the stack for each call. Since you don't have a copy constructor, the copies point to the original, not themselves. – Barmar Mar 23 '17 at 02:26
  • the 'return' will copy the local object to the vector object, so maybe you can write the assignment operator, copy the data and let the my_pointer be 'this'. code like this: MyClass& operator = (const MyClass& other) { my_data = other.my_data; my_pointer = this; return *this; } – Tingur Mar 23 '17 at 08:23

0 Answers0