I have a simple function that I simplified to return just a dummy list (to ensure its not some logic error)
vector<AttrValue>* QueryEvaluator::getCandidateList(...) {
...
values.clear();
values.push_back(2);
values.push_back(3);
cout << "values is of size " << values.size() << endl;
return &values;
}
then in a cppunit test:
vector<AttrValue>* candidateList0 = evaluator->getCandidateList(cl, 0);
cout << candidateList0->size() << endl;
But problem is size(), in the test, is always 0 even though the cout message prints the correct size 2. What might be wrong?
I tried a simple program and it appears to be fine …
#include <iostream>
#include <vector>
using namespace std;
vector<int>* test() {
vector<int> vec { 2, 3, 6, 1, 2, 3 };
return &vec;
}
int main() {
cout << test()->size() << endl;
return 0;
}
You are returning a the address of temporary from
getCandidateListfunction, the object is release when function returns. access to it is undefined behavior. You could just return the vector out, RVO should come to apply and elide the copy:Try:
the temporary vector is released when getCandidateList function returns. The program has undefined behavior.