I have a class with a std::vector data member e.g.
class foo{
public:
const std::vector getVec(){return myVec;} //other stuff omitted
private:
s
Another reason why this assert can trigger is if you would allocate "foo" with 'malloc' instead of 'new', effectively skipping the constructor(s).
It's unlikely to happen to a project developed from scratch in C++, but when converting plain-C code to C++ (replacing a static array[] in some struct with an stl-vector) you might just not realise that dynamic instances of said struct (and the members inside) are not going to have their constructor called - unless you also change 'malloc' to 'new'.
You are returning a copy of the vector. Because you are returning by value - your call to begin() and end() are for completely different vectors. You need to return a const & to it.
const std::vector<int> &getVec(){return myVec;}
I would do this slightly differently though. I'd make the class act a little like a standard container
class Data
{
public:
typedef std::vector<int>::const_iterator const_iterator;
const_iterator begin() const { return myVec.begin(); }
const_iterator end() const { return myVec.end(); }
};
Data::const_iterator i=myFoo.begin();
while(i != myFoo.end())
{
//
}
Change
const std::vector<int> getVec(){return myVec;}
to
const std::vector<int>& getVec(){return myVec;}
well, I don't think vector copy could be the only cause, that seems to be too obivious to me.
in my case I just find that corrupted stack, heap, uninteneded changes could also result in this failure, and it will in fact hiding the underlying reason. in my case, I changed to use indexer to iterate through and find the root cause.
Because you are returning by value - your call to begin() and end() are for completely different vectors. You need to return a const & to it
You are making a constant copy of the member vector, not accessing the member vector.
Change this:
const std::vector<int> getVec(){return myVec;} //other stuff omitted
to this:
const std::vector<int> & getVec(){return myVec;} //other stuff omitted
To go a little deeper, the iterator you get from this statement:
std::vector<int>::const_iterator i = myFoo.getVec().begin();
is an iterator to the temporary copy of your vector, which goes away after that statement executes, invalidating the iterator.