471,092 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,092 software developers and data experts.

return reference to local variable?

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<Pairpairs;
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?
Jun 27 '08 #1
2 1697
On May 30, 12:38 pm, zhen...@gmail.com wrote:
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<Pairpairs;
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.
Jun 27 '08 #2
zh*****@gmail.com wrote:
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<Pairpairs;
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.

--
Jim Langston
ta*******@rocketmail.com
Jun 27 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Kench | last post: by
25 posts views Thread by cppaddict | last post: by
14 posts views Thread by Gama Franco | last post: by
6 posts views Thread by romerun | last post: by
4 posts views Thread by | last post: by
7 posts views Thread by George2 | last post: by
68 posts views Thread by Jim Langston | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.