[英]why references to members of a class in a vector point to the same value for different objects?
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.但是当对象被放置在一个向量中时,所有对象的 ref 变量都是相同的。
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块引用
std::vector
requires an appropriately written assignment operator. std::vector
需要适当编写的赋值运算符。
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.最好的办法是删除引用类成员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.