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
}
The problem with this code is that trunk.left()
returns a copy of the branch, not a reference to the branch. Consequently, your focus3
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 dereferencing focus3
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 make focus3
a const reference, which extends the lifetime of the temporary to the lifetime of the reference.
精彩评论