Reputation: 31
Let's have a simple class:
class Var
{
public:
explicit Var(const std::string& name, const double v)
: value(v), ref(value), _name(name) {};
~Var() {};
double value{};
double& ref;
void print()
{
std::cout << _name << ":\n";
std::cout << "\tvalue = " << value << " (" << &value << ")\n";
std::cout << "\t ref = " << ref << " (" << &ref << ")\n\n";
}
private:
std::string _name;
};
In this case everything is fine:
Var v0("v0", 0.0);
Var v1("v1", 1.0);
Var v2("v2", 2.0);
v0.print();
v1.print();
v2.print();
Output is:
v0:
value = 0 (000000DDE3D3F878)
ref = 0 (000000DDE3D3F878)
v1:
value = 1 (000000DDE3D3F8E8)
ref = 1 (000000DDE3D3F8E8)
v2:
value = 2 (000000DDE3D3F958)
ref = 2 (000000DDE3D3F958)
But when objects are placed in a vector, the ref variable is the same for all objects.
vector<Var> V{};
for (size_t i = 0; i < 3; i++)
{
std::string name = "V[" + std::to_string(i) + "]";
V.push_back(Var(name, i));
}
for (size_t i = 0; i < 3; i++)
V[i].print();
output:
V[0]:
value = 0 (000002B594F55C70)
ref = 2 (000000DDE3D3FA88)
V[1]:
value = 1 (000002B594F55CA8)
ref = 2 (000000DDE3D3FA88)
V[2]:
value = 2 (000002B594F55CE0)
ref = 2 (000000DDE3D3FA88)
what am I doing wrong?
Blockquote
Upvotes: 2
Views: 67
Reputation: 234665
std::vector
requires an appropriately written assignment operator.
The one the compiler provides is useless for your class since the reference is not rebound. So you need to write it out yourself. And that's not trivial:
Assignment operator with reference members
The best thing to do though is to drop the reference class member.
Upvotes: 4