std::vector 中止问题
我对下面的示例遇到困难,最后一行产生“已调用中止”错误。我不明白为什么会这样。
在这种情况下,为了清楚起见,我使用 (*abc).def 而不是 abc->def 。
#include <iostream>
#include <string>
#include <vector>
class branch
{
public:
unsigned short n;
std::vector<branch> branches;
branch left()
{
return branches.at(0);
}
};
void main()
{
branch trunk = branch();
trunk.n = 0;
branch b1, b2;
b1.n = 0;
b2.n = 5;
b1.branches.push_back(b2);
trunk.branches.push_back(b1);
branch* focus1 = &(trunk.branches.at(0));
branch* focus3 = &(trunk.left());
std::cout<<trunk.left().branches.at(0).n<<std::endl; // ok
std::cout<<(*focus1).branches.at(0).n<<std::endl; // ok
std::cout<<(*focus1).left().n<<std::endl; // ok
std::cout<<(*focus3).branches.at(0).n<<std::endl; // problem
}
I'm having diffuculty with the example below, the last line is producing an "abort has been called" error. I don't see why this should be.
I'm using (*abc).def instead of abc->def for clarity in this case.
#include <iostream>
#include <string>
#include <vector>
class branch
{
public:
unsigned short n;
std::vector<branch> branches;
branch left()
{
return branches.at(0);
}
};
void main()
{
branch trunk = branch();
trunk.n = 0;
branch b1, b2;
b1.n = 0;
b2.n = 5;
b1.branches.push_back(b2);
trunk.branches.push_back(b1);
branch* focus1 = &(trunk.branches.at(0));
branch* focus3 = &(trunk.left());
std::cout<<trunk.left().branches.at(0).n<<std::endl; // ok
std::cout<<(*focus1).branches.at(0).n<<std::endl; // ok
std::cout<<(*focus1).left().n<<std::endl; // ok
std::cout<<(*focus3).branches.at(0).n<<std::endl; // problem
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码的问题在于 trunk.left() 返回分支的副本,而不是对该分支的引用。因此,您的 focus3 指针指向一个临时对象,该对象将在该行代码执行完毕后立即被清除。因此,当您尝试在最后一行取消引用
focus3
时,您将跟踪指向垃圾数据的指针,这会导致崩溃。要解决此问题,请让
left
返回对分支的引用,或将focus3
设置为 const 引用,这会将临时引用的生命周期延长到引用的生命周期。The problem with this code is that
trunk.left()
returns a copy of the branch, not a reference to the branch. Consequently, yourfocus3
pointer is pointing at a temporary object that's immediately going to be cleaned up after that line of code finishes executing. Consequently, when you try dereferencingfocus3
on the last line, you're following a pointer to garbage data, which causes the crash.To fix this, either have
left
return a reference to the branch, or makefocus3
a const reference, which extends the lifetime of the temporary to the lifetime of the reference.