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?
#include <iostream>
#include <vector>
usingnamespace std;
class myClass
{
vector<int> m_vector;
public:
myClass()
{
for (size_t i = 0; i < 10; i++) {
this->m_vector.push_back(i);
}
}
const vector<int>& getVector() const
{
returnthis->m_vector;
}
};
const myClass generate()
{
myClass obj;
return obj;
}
int main()
{
myClass obj;
const vector<int> *x = &obj.getVector();
size_t i = 0;
cout << "That is what the vector looks like (*x): ";
for (; i < 10; i++) {
cout << x->at(i) << " ";
}
cout << endl;
const vector<int> *v = &(generate().getVector());
cout << "The vector from *v: ";
for (i = 0; i < 10; i++) {
cout << v->at(i) << " ";
}
cout << endl;
vector<int> *y = const_cast< vector<int>* >(x);
y->at(0) = 1000;
cout << "The vector from *x again: ";
for (i = 0; i < 10; i++) {
cout << x->at(i) << " ";
}
cout << endl;
return 0;
}
that is the output
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.