return reference to local variable?

Z

zheng4t

I am learning C++. I found the following code in the book The C++
Programming Language by Bjarne Stroustrup.

struct Pair {
string name;
double val;
};

vector<Pair> pairs;
double& value(const string& s)
{
Pair p = {s, 0};
pairs.push_back(p);
return pairs[pairs.size() - 1].val
}

The push_back takes a reference as parameter. So p would not be
copied. So the return of the function will be a reference to a (part
of) local variable p. What I am missing here?
 
Z

zhou.zhihua.mail

I am learning C++. I found the following code in the book The C++
Programming Language by Bjarne Stroustrup.

struct Pair {
string name;
double val;

};

vector<Pair> pairs;
double& value(const string& s)
{
Pair p = {s, 0};
pairs.push_back(p);
return pairs[pairs.size() - 1].val

}

The push_back takes a reference as parameter. So p would not be
copied. So the return of the function will be a reference to a (part
of) local variable p. What I am missing here?

I think the push_back implementation will copy the parameter.
 
J

Jim Langston

I am learning C++. I found the following code in the book The C++
Programming Language by Bjarne Stroustrup.

struct Pair {
string name;
double val;
};

vector<Pair> pairs;
double& value(const string& s)
{
Pair p = {s, 0};
pairs.push_back(p);
return pairs[pairs.size() - 1].val
}

The push_back takes a reference as parameter. So p would not be
copied. So the return of the function will be a reference to a (part
of) local variable p. What I am missing here?

push_back will copy the variable to the vector. Since the vector is global,
the vector lives beyond the function, and so the the pair it copied. It is
returning a reference to the variable in the vector, not the local variable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top