C++ strange behaviour mutator vector -
i've been working on work school have create client class 4 string, 4 int , vector(int) last argument. problem is, when want print of vector's elements, if use mutator directly, printing nonsence.
vector<int> v_int; vector<int>::iterator it_v_i; v_int.push_back(2); v_int.push_back(3); v_int.push_back(7); v_int.push_back(1); client client("nom1", "prenom1", "adress1", "city1", "comment1", 1240967102, 44522, 5, 10, v_int); v_int = client.getidresources(); (it_v_i = v_int.begin(); it_v_i != v_int.end(); it_v_i++) { cout << *it_v_i << ", "; }
print 2,3,7,1 expected, following code
for (it_v_i = client.getidresources().begin(); it_v_i != client.getidresources().end(); it_v_i++) { cout << *it_v_i << ", "; }
print unidentified number (like 3417664...), unidentified number, 7, 1
i don't understand why happening
edit :
constructor :
client::client(const string& name, const string& surname, const string& adress, const string& city, const string& comment, const int& phonenb, const int& postalcode, const int& termappointment, const int& priority, const vector<int>& idresources) : name(name), surname(surname), adress(adress), city(city), comment(comment), phonenumber(phonenb), postalcode(postalcode), termappointment(termappointment), priority(priority), idresources(idresources)
{ }
mutator :
std::vector<int> getidresources() const{ return idresources; }
the problem in second snippet two temporary vector
s being used obtain begin()
, end()
iterators (assuming declaration std::vector<int> client.getidresources()
, not std::vector<int>& client.getidresources()
). means it_v_i
referring elements of destructed std::vector
. when it_v_i
dereferenced causes undefined behaviour.
to make second code snippet function correctly reference std::vector
needs returned client.getidresources()
. however, returning references internal class members introduces other problems, such lifetime issues.
Comments
Post a Comment