C++ passing by reference and casting confusion
Say I have Object o which contains a vector defined as:
std::vector<V *> V;
and I have a getter:
inline std::vector<V *>& getV() { return V; };
if I am passing a parameter in by reference:
void A::function(Object& o)
and trying to access items in std::vector V;
How should I do this?
void A::function(Object& _o)
{
for (int f=0; f < _o.getV().size(); f++)
{
V* _v = _o.getV().at(f);
std::string s = _v->getName().c_str();
std::cout << "V: " << _v->getName().at(f) << std::endl;
std::cout << "V: " << s << std::endl;
}
}
}
What mistake am I making if I am crashing when trying to acces
_v->getName() above.
If I look at the crash I do see that _v has positions filled:
V std::__1::vector<V *, std::__1::allocator<V *> > size=8
[0] V * 0xbfffd658 0xbfffd658
[1] V * 0xbfffd658 0xbfffd658
[2] V * 0xbfffd658 0xbfffd658
[3] V * 0xbfffd658 0xbfffd658
[4] V * 0xbfffd658 0xbfffd658
[5] V * 0xbfffd658 0xbfffd658
[6] V * 0xbfffd658 0xbfffd658
[7] V * 0xbfffd658 0xbfffd658
UPDATE: So it seem that the previous dev did something like this at one point
in a .h Object* o1;
in .a cpp
void B::function(Object& _o)
{
o1 = &_o;
.... does stuff with o1 .....
}
in another .cpp passes in the original object o to do stuff with it:
void A::function(Object& _o)
{
for (int f=0; f < _o.getV().size(); f++)
{
V* _v = _o.getV().at(f);
std::string s = _v->getName().c_str();
std::cout << "V: " << _v->getName().at(f) << std::endl;
std::cout << "V: " << s << std::endl;
}
}
}
No comments:
Post a Comment