引用 vector::front 可以,但 vector::begin 不行
我有这段代码:
cerr << client->inventory.getMisc().front()->getName() << endl;
vector<itemPtr>::iterator it;
it = client->inventory.getMisc().begin();
cerr << (*it)->getName() << endl;
让我解释一下:
client
是一个 tr1::shared_ptr
,它指向一个具有名为 inventory< 的成员的对象/code> 具有可通过
getMisc()
访问的私有 vector
成员。 itemPtr
是 tr1::shared_ptr
的类型定义,getName()
返回私有 std::stringItem
的 code> 成员。
本质上,client->inventory.getMisc()
归结为 std::vector
,我正在尝试获取其第一个元素的迭代器。
问题是第四行出现段错误。显然它指向的迭代器或shared_ptr是无效的。我使用第一个 cerr 语句来测试向量本身是否有效,并且它按应有的方式打印,所以我认为它是有效的。
我做错了什么吗?或者,你们会做什么来调试这个?
I have this bit of code:
cerr << client->inventory.getMisc().front()->getName() << endl;
vector<itemPtr>::iterator it;
it = client->inventory.getMisc().begin();
cerr << (*it)->getName() << endl;
Let me explain that a bit:
client
is a tr1::shared_ptr
that points to an object that has a member named inventory
that has a private vector<itemPtr>
member accessible by getMisc()
. itemPtr
is a typedef for tr1::shared_ptr<Item>
, and getName()
returns a private std::string
member of Item
.
Essentially, client->inventory.getMisc()
boils down to a std::vector
, and I'm trying to get an iterator to its first element.
The problem is that the fourth line segfaults. Apparently either the iterator or the shared_ptr it points to is invalid. I used the first cerr statement to test if the vector itself was valid, and it prints as it should, so I think it is.
Is there anything I'm doing wrong? Alternatively, what would you guys do to debug this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getMisc
的签名到底是什么?如果您实际上返回的是
std::vector
,那么您将返回列表的副本。在这种情况下,第一个访问模式将(缓慢地)起作用,因为临时副本直到front
完成执行之后才会被销毁,此时itemPtr
本身已被复制变成临时的。第二个失败是因为在使用begin
获取迭代器后,临时超出范围并被销毁,使刚刚创建的迭代器挂起。Exactly what is the signature of
getMisc
?If you're actually returning a
std::vector<itemPtr>
then you are returning a copy of the list. In that case, the first access pattern will work (slowly) because the temporary copy doesn't get destroyed until afterfront
finishes executing, by which time theitemPtr
itself is copied into a temporary. The second fails because after getting at the iterator withbegin
, the temporary falls out of scope and is destroyed, leaving the just-created iterator hanging.单步执行代码,看看
front()
返回的内容和(*it)
返回的内容有什么不同。Step though the code to see what's different about what
front()
returns and what(*it)
returns.你确定向量不为空吗?
front
和begin
的行为可能略有不同,并且front
纯粹是偶然工作的,而迭代器本身的额外检查会在以下情况下导致 seg 错误:它被使用了。Are you sure that the vector isn't empty? It's possible that
front
andbegin
behave slightly differently andfront
could work by pure chance, while additional checks in the iterator itself cause the seg fault when it's used.