Domanda

I've been working on a work for school where we have to create a Client class with 4 string, 4 int and a vector(int) as the last argument. The problem is, when i want to print all of the vector's elements, if i use my mutator directly, it is 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();
for (it_v_i = v_int.begin(); it_v_i != v_int.end(); it_v_i++) {
    cout << *it_v_i << ", ";
}

print 2,3,7,1 as expected, but the 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 really don't understand why this is 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; }
È stato utile?

Soluzione

The problem is that in second snippet two temporary vectors are being used to obtain the begin() and end() iterators (assuming the declaration is std::vector<int> client.getIdResources() and not std::vector<int>& client.getIdResources()). This means that it_v_i is referring to the elements of a destructed std::vector. When it_v_i is dereferenced it causes undefined behaviour.

To make the second code snippet function correctly a reference to the std::vector needs to be returned by client.getIdResources(). However, returning references to internal class members introduces other problems, such as lifetime issues.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top