Please correct me if i am wrong.
From this code, and for my surprise, I realized that the getter member function returns the std::vector by value (by default).
// Example program
#include <iostream>
#include <vector>
usingnamespace std;
class C {
private:
std::vector<int> v;
public:
C() {
v.resize(10);
}
std::vector<int> getv() {
return v;
}
void setv( std::vector<int> v1 ) {
v = v1;
}
};
int main()
{
std::vector<int> v2;
C myC;
std::cout << "v content in myC is " << endl;
for(int d : myC.getv()) std::cout << d << ' ';
std::cout << endl;
v2 = myC.getv();
std::cout << "after v2 = myC.getv(), v2 content is " << endl;
for(int d : v2) std::cout << d << ' ';
std::cout << endl;
v2[4] = 1;
std::cout << "after v2[4] = 1;, v2 content is " << endl;
for(int d : v2) std::cout << d << ' ';
std::cout << endl;
std::cout << "but now, v content is " << endl;
for(int d : myC.getv()) std::cout << d << ' ';
std::cout << endl;
myC.setv(v2);
std::cout << "after myC.setv(v2), v content is " << endl;
for(int d : myC.getv()) std::cout << d << ' ';
std::cout << endl;
std::cout << "and v2 content is " << endl;
for(int d : v2) std::cout << d << ' ';
std::cout << endl;
return 0;
}
My question is:
What is the right way to code getters and setters with these kind of data (std::vectors).
I don't want to enter in philosophical topics like the one exposed in: http://www.cplusplus.com/forum/lounge/101305/
That is great!
Yet I just want to receive an answer in terms of the pros and cons about coding getters and setters in one way or another.
IMO your class makes no sense. You're doing all of the processing outside the class so there is really no need for the class, just use a non-class vector instance.
> returns the std::vector by value (by default).
There is no «by default», you tell it to return a copy, it'll return a copy, you tell it to return a reference, it'll return a reference.
Well,
Please, excuse me if I don't understand something obvious.
I followed your indication ne555, and the output in the program, is:
v content in myC is
0 0 0 0 0 0 0 0 0 0
after v2 = myC.getv(), v2 content is
0 0 0 0 0 0 0 0 0 0
after v2[4] = 1;, v2 content is
0 0 0 0 1 0 0 0 0 0
but now, v content is
0 0 0 0 0 0 0 0 0 0
after myC.setv(v2), v content is
0 0 0 0 1 0 0 0 0 0
and v2 content is
0 0 0 0 1 0 0 0 0 0
after the modification of v2 (which is supposed to be a reference to v) by means of v2[4] = 1;
v content is
0 0 0 0 0 0 0 0 0 0
but v2 is
0 0 0 0 1 0 0 0 0 0
Again, excuse me if I am missing some obvious detail.
The "&" seems to make no effect in the code at all.