Given the code
#include <iostream>
#include <vector>
class Entity {
public:
Entity(const int x, const int y) :
x(x), y(y)
{
this->entities.push_back(*this);
}
int x, y;
std::vector<Entity> entities;
};
int main() {
auto p = Entity(10, 20);
std::cout << p.entities.size() << '\n';
std::cout << p.x << ' ' << p.y << "\n\n";
std::cout << p.entities[0].entities.size() << '\n';
std::cout << p.entities[0].x << ' ' << p.entities[0].y << '\n';
return 0;
}
When entities.push_back is called, the Entity should be copied to the vector. When copied all members should have their copy constuctors called in the following order: (x, y, entities). The problem is in the entities constructor, the "std::vector" constructor should call the "Entity" constructor that will call the "std::vector" constructor again, resulting in a infinite loop.
But according to the output:
1
10 20
0
10 20
The "std::vector" copy constructor is not called.
Where is my error? I'm forgetting some implementation detail?
CodePudding user response:
the "std::vector" constructor should call the "Entity" constructor that will call the "std::vector" constructor again, resulting in a infinite loop
Nope.
The std::vector<Entity> copy constructor will call the Entity copy constructor.
The Entity copy constructor copies the member vector as it currently exists (empty). It does not run the code in the two-element Entity constructor that push_back something to the vector.
CodePudding user response:
You're copying yourself in a constructor, which is generally a bad practice since the object is not yet fully constructed. In this case, the vector is still empty when you call push_back.
