I am new to C++ and I really cannot understand what is wrong in the following.
I got a segmentation fault
when I try to access the vector from the main function (I can see the Vector received
message) while I would expect that the variable asd
in the main
should refer to the memory allocated by the function get_vector
.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<double>& get_vector()
{
cout << "Enter function" << endl;
vector<double> asd;
asd.push_back(10.);
cout << "Exit function" << endl;
return asd;
}
int main() {
vector<double>& asd = get_vector();
cout << "Vector received" << endl;
cout << asd[0] << endl;
}
Another point is that when compiling it with g++ I get a warning saying warning: reference to local variable ‘asd’ returned
. I imagine this is something very bad... could someone tell me what is the problem or give me some link where I can find an explanation to that?
Thank you