I have a couple classes that have member vectors, and I want to return these vectors (or a copy of them, I only need them for reading purposes) with a method call. I would prefer returning a copy, rather than the actual one to ensure the data doesn't get changed. How would I do this?
That is what the vector looks like (*x): 0 1 2 3 4 5 6 7 8 9
The vector from *v: 0 0 2 3 4 5 6 7 8 9
The vector from *x again: 1000 1 2 3 4 5 6 7 8 9
what happend here?
@v:
we created a temporary object and get a pointer to its vector, when the object is destroyed, it is not guranteed that the reference to the vector is valid after that!
or think of a destructor of myClass that calls this->m_vector.clear(); and then your pointer points to an empty vector.
@y & x:
its possible to remove the const! so you can edit the internal vector, even though you returned a const reference.
sure, these problems maybe never occur in your program. but this is why you should not return a handle to members of a class. always return a copy
Note that subverting C++'s type system through const_cast is undefined behavior according to the standard. You should already be suspicious of line 50, before even trying to compile the program.