Quick Q: Is it still bad practice to return a vector from a function?

 

Here's another FAQ about modern C++11 style, and how C++11 is simpler than classic C++, including that this affects how we design our interfaces to make them simpler and easier to read and use.

However, be sure to read through the comments, because they cover several considerations including when it's safe to start relying on the simpler C++11 semantics as you migrate a code base from C++98 to C++11 and may still have to support C++98 clients for a while.

In C++, is it still bad practice to return a vector from a function?

Short version: It's common to return large objects—such as vectors/arrays—in many programming languages. Is this style now acceptable in C++0x if the class has a move constructor, or do C++ programmers consider it weird/ugly/abomination?

Long version: In C++0x is this still considered bad form?

std::vector<std::string> BuildLargeVector();

...

std::vector<std::string> v = BuildLargeVector();

 

[...]

Add a Comment

Comments are closed.

Comments (3)

0 0

Bjarne Stroustrup said on Jan 11, 2013 06:47 PM:

It is recommended.
0 0

Balakrishnan B said on Jan 12, 2013 03:41 AM:

I thought returning by value was as good as taking inval arguments in C++11. But this Q&A has confused me. Its obvious returning by value is neat and clean in terms of style. But What is the final verdict in terms of performance?
a) Returning by value is always (100 %) equivalent or better than taking an inval
b) Taking inval is always (100%) equivalent or better than returning by value
c) Some cases Returning by value is efficient and in some other cases taking inval is efficient.

If c), what are those cases?
Assuming 1)a good compiler with latest version like gcc, MSVC, clang, icc. 2) The object returned by value has a no_expect (does it matter?) move constructor.
1 0

Bjarne Stroustrup said on Jan 12, 2013 07:01 AM:

Have a look at my "Tour of C++" (http://isocpp.org/tour), especially section 3.3 of "Part 2: Abstraction Mechanisms". We can now return large collections of data by moving them, e.g., a std::vector can be returned cheaply from a function. This eliminates a class of memory management problems, and is quite different from returning an iterator to something owned by some other function.