包含引用的对象向量
我有以下结构:
struct Transaction {
Transaction(Book& bb, Patron& pp, Date dd)
: b(bb), p(pp), d(dd) { }
Book& b;
Patron& p
Date d;
};
当我尝试使用 push_back
将 Transaction
类型的对象放入 vector
时,它获胜不工作。一屏错误就破灭了。
是因为我有引用作为我的对象的成员吗?
I have the following struct:
struct Transaction {
Transaction(Book& bb, Patron& pp, Date dd)
: b(bb), p(pp), d(dd) { }
Book& b;
Patron& p
Date d;
};
When I try to put an object of type Transaction
into a vector<Transaction>v_t
with a push_back
, it won't work. A screenful of errors breaks lose.
Is it because I have references as members of my object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要该类型的赋值和复制运算符,因为它包含引用。 STL 容器对象必须是可复制和可分配的(不幸的是,这对于您的引用来说是不可能的)。
检查此线程:
http://cboard .cprogramming.com/cplusplus-programming/106779-copy-constructor-class-const-reference-member.html
它讨论了问题和一些替代解决方案,尽管它基本上说容器类型中没有引用成员。
You'll need an assignment and copy operator for the type since it contains a reference. STL container objects must be copyable AND assignable (and this won't be possible with your reference unfortunately).
Check this thread:
http://cboard.cprogramming.com/cplusplus-programming/106779-copy-constructor-class-const-reference-member.html
It discusses the problem and some alternate solutions, though it basically says don't have a reference member in container type.
STL 是基于值的,不能很好地与引用配合使用。您可以进入 一场可怕的混乱试图绕过这条规则。
将
b
、p
、d
成员转换为值或shared_ptr
。STL is value-based and doesn't play well with references. You can get into a horrible tangle trying to get around this rule.
Turn the
b
,p
,d
members into values orshared_ptr
s.STL 不适用于引用,因为您不能使用赋值运算符来分配引用(而不是复制)。
您应该使用指针,例如:
STL doesn't work with references because you can't have assignment operator that will assign a reference(not copy).
You should use pointers instead like:
社区 wiki,因为这几乎肯定会调用 UB。
如果您有复制构造函数,则可以使用放置新来创建赋值运算符:
这可能适用于您的计算机、编译器和特定的优化设置。话又说回来,可能不会。或者,当您的操作系统自动更新 C++ ABI 库时,它可能会突然停止工作。或者,当您将其交付给拥有稍微不同版本的 C++ ABI 库的客户时,它可能会突然停止工作。
无论您如何削减它,更改引用都是未定义的行为。
Community wiki, because this almost certainly invokes UB.
If you have a copy constructor you can make an assignment operator using placement new:
This might work with your computer, with your compiler, with a specific optimization setting. Then again, it might not. Or it might suddenly stop working when your operator system auto-updates the C++ ABI library. Or it might suddenly stop working when you deliver it to your customer who has a slightly different version of the C++ ABI library.
No matter how you cut it, changing a reference is undefined behavior.