Optimisation, function returns, STL containers

S

Simon Elliott

What optimisation do compilers typically provide when passing STL
containers around?

For example, if I do something like this:

struct Tbloggs
{
std::string s1;
};
typedef std::vector<Tbloggs> TbloggsList;
typedef std::vector<TbloggsList> TbloggsListContainer;

TbloggsList getBloggsList(void)
{
TbloggsList tempBloggsList;
Tbloggs b1;
tempBloggsList.push_back(b1);
return(tempBloggsList);
}

TbloggsListContainer myBloggsListContainer;
TbloggsList myBloggsList = getBloggsList();
myBloggsListContainer.push_back(myBloggsList);

In theory there's a whole lot of unnecessary copying going on here, in
the "push_back"s and the getBloggsList() return. How much of this is the
compiler allowed to optimise away?
 
V

Victor Bazarov

Simon Elliott said:
What optimisation do compilers typically provide when passing STL
containers around?

The same as for any other classes. That's the whole point.
For example, if I do something like this:

struct Tbloggs
{
std::string s1;

Supposedly 'std::string' has been defined here...
};
typedef std::vector<Tbloggs> TbloggsList;
typedef std::vector<TbloggsList> TbloggsListContainer;

TbloggsList getBloggsList(void)
{
TbloggsList tempBloggsList;
Tbloggs b1;
tempBloggsList.push_back(b1);
return(tempBloggsList);
}

TbloggsListContainer myBloggsListContainer;
TbloggsList myBloggsList = getBloggsList();
myBloggsListContainer.push_back(myBloggsList);

In theory there's a whole lot of unnecessary copying going on here, in
the "push_back"s and the getBloggsList() return. How much of this is the
compiler allowed to optimise away?

The construction of 'myBloggList' object is permitted to happen
"in place" (see 12.8/15). It's called "return value optimisation".

Victor
 
L

lilburne

Victor said:
The construction of 'myBloggList' object is permitted to happen
"in place" (see 12.8/15). It's called "return value optimisation".

Though it won't happen in assignments, so you'll need to be
carefull of any other statements like:

myBloggsList = getBloggsList();

which isn't a construction. But you should be aware of this
with any object that is returned by value.
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top