Is it better to pass STL container classes by value or by reference?

Which is standard? Would it be better to pass something like a vector by value like the built in types or by reference more like the object types?
Last edited on
If you pass it by value, you get a copy of it, so any changes will not appear in the original. Also, since it is copied, it takes longer and uses more memory. So it is usual to pass it by reference (const reference if you don't want to modify it), unless of course you actually want a new copy of it to alter while not altering the original.
closed account (S6k9GNh0)
There is no standard in this case. They're both common and both have ups and downs. Passing by value is good for small classes and types. Other than that, you should pretty much create date and pass a pointer to the data you just created.

Also note, references are the exact same as pointers. Just different interface.
But passing STL containers, no matter what they are or how many elements they contain, is very expensive, and I would never advocate passing any STL containers (strings included) by value unless by passing by const reference the function has to make a copy of it anyway.

For example, if you use the copy-swap idiom for implementing assignment operators in an exception-safe manner, it makes sense to pass by value, since a copy would need to be made anyway.

Simple, stupid example (stupid because the default assignment operator suffices; no need to write one):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MyClass {
  public:
     // Passing by value:
     MyClass& operator=( MyClass c ) {
         std::swap( x, c.x );
         std::swap( y, c.y );
         std::swap( z, c.y );
         return *this;
     }   

     // Or, passing by const reference:
    MyClass& operator=( const MyClass& c ) {
        MyClass temp( c );       // Copy c
        std::swap( x, temp.x );
        std::swap( y, temp.y );
        std::swap( z, temp.z );
        return *this;
    }

  private:
     int x;
     int y;
     int z;
};

Topic archived. No new replies allowed.