Why is the function signature of push_back
the following?
void push_back (const value_type& val);
The value passed is copied into the container, why not make a copy directly into the argument list?
void push_back (value_type val);
Why is the function signature of push_back
the following?
void push_back (const value_type& val);
The value passed is copied into the container, why not make a copy directly into the argument list?
void push_back (value_type val);
The answer is to avoid making yet another copy. Take a look at this simple example that illustrates the difference between using value_type
and const value_type&
.
#include <iostream>
using namespace std;
struct A
{
A() {}
A(A const& copy)
{
cout << "Came to A::A(A const& copy)\n";
}
void print() const
{
cout << "Came to A:print()\n";
}
};
void foo(A const& a)
{
A copy = a;
copy.print();
}
void bar(A a)
{
A copy = a;
copy.print();
}
int main()
{
A a;
foo(a);
bar(a);
}
Output of running the program:
Came to A::A(A const& copy) Came to A:print() Came to A::A(A const& copy) Came to A::A(A const& copy) Came to A:print()
Notice the additional call to the copy constructor due to the call to bar
. For some objects, that additional copy construction and the corresponding destruction can be very expensive when the operation is carried out millions of times.
Here's what an extremely simplified push_back
into a vector might look like when implemented with each of those interfaces:
// by reference
void push_back (value_type const & val)
{
// Copy val into its designated place.
new (m_data_ptr + m_len++) value_type (val);
}
// by value
void push_back (value_type val)
{
// Copy val into its designated place.
// In C++11, this copy may not happen if value_type is movable. But that's
// not always the case. (you have to use std::move too.)
new (m_data_ptr + m_len++) value_type (val);
}
They look the same, don't they?
The problem is when you try calling them, specially the pass-by-value version:
string s;
...
v.push_back (s);
If push_back
accepts its parameter by reference (i.e. value_type & val
) then a reference to the existing object s
is passed into the function and no copies are made here. Of course, we still need one copy inside the function, but that's kinda necessary.
However, if push_back
is written to get its parameter by value (i.e. value_type val
) then a copy will be made of the s
string right at the call site, onto the stack and into the argument that will be named val
. Here, val
is not a reference to a string, it is a string and it must come from somewhere. This extra copy is what drove the designer(s) of STL and most sensible C++ libraries to adopt pass-by-reference as the preferred choice for many situations (and in case you are wondering, that const
is there to tell the caller that now that this function can modify its precious object, since a reference to it is being given to the function, it won't!)
By the way, this discussion mostly applies to C++98 (i.e. the old C++.) The current C++ has Rvalue references and moving and perfect forwarding which provide for more interface options and the opportunity for cleaner and more precise and more efficient interfaces/implementations, but also make this topic a bit more complicated.
In C++11, there are two overloads of push_back
(as well as a new member emplace_back
) on vector and other containers.
The push_back
s are:
void push_back (value_type const & val);
void push_back (value_type && val);
The second one is the correct version of what you are suggesting (i.e. it won't be ambiguous for the compiler.) It lets the implementation move the value out of that rvalue reference, and lets the compiler generate code to call the faster version if appropriate.
For backward-compatibility reasons (and probably a few other minor ones,) the old push_back
signature cannot be removed from C++.
Imagine you have this class:
class Data {
public:
Data() { }
Data(const Data& data) { std::cout << " copy constructor\n";}
Data(Data&& data) { std::cout << " move constructor\n";}
Data& operator=(const Data& data) { std::cout << " copy assignment\n"; return *this;}
Data& operator=(Data&& data) { std::cout << " move assignment\n"; return *this;}
};
Note, a good C++11 compiler should define all these functions for you (Visual Studio doesn't) but I'm defining them here for debug output.
Now, if you wanted to write a class to store one of these classes I might use pass-by-value like you suggest:
class DataStore {
Data data_;
public:
void setData(Data data) { data_ = std::move(data); }
};
I am taking advantage of C++11 move semantics to move the value to the desired location. I can then use this DataStore
like this:
Data d;
DataStore ds;
std::cout << "DataStore test:\n";
ds.setData(d);
std::cout << "DataStore test with rvalue:\n";
ds.setData(Data{});
Data d2;
std::cout << "DataStore test with move:\n";
ds.setData(std::move(d2));
Which has the following output:
DataStore test:
copy constructor
move assignment
DataStore test with rvalue:
move assignment
DataStore test with move:
move constructor
move assignment
Which is fine. I have two moves in the last test which might not be optimum but moves are typically cheap so I can live with that. To make it more optimum we would need to overload the setData
function which we will do later but that's probably premature optimization at this point.
But now imagine we have a copyable but unmovable class:
class UnmovableData {
public:
UnmovableData() { }
UnmovableData(const UnmovableData& data) { std::cout << " copy constructor\n";}
UnmovableData& operator=(const UnmovableData& data) { std::cout << " copy assignment\n"; return *this;}
};
Before C++11, all classes were unmovable so expect to find lots of them in the wild today. If I needed to write a class to store this I can't take advantage of move semantics so I would probably write something like this:
class UnmovableDataStore {
UnmovableData data_;
public:
void setData(const UnmovableData& data) { data_ = data; }
};
and pass by reference-to-const. When I use it:
std::cout << "UnmovableDataStore test:\n";
UnmovableData umd;
UnmovableDataStore umds;
umds.setData(umd);
I get the output:
UnmovableDataStore test:
copy assignment
with only one copy as you would expect.
You could also have a movable but noncopyable class:
class UncopyableData {
public:
UncopyableData() { }
UncopyableData(UncopyableData&& data) { std::cout << " move constructor\n";}
UncopyableData& operator=(UncopyableData&& data) { std::cout << " move assignment\n"; return *this;}
};
std::unique_ptr
is an example of a movable but noncopyable class. In this case I would probably write a class to store it like this:
class UncopyableDataStore {
UncopyableData data_;
public:
void setData(UncopyableData&& data) { data_ = std::move(data); }
};
where I pass by rvalue reference and use it like this:
std::cout << "UncopyableDataStore test:\n";
UncopyableData ucd;
UncopyableDataStore ucds;
ucds.setData(std::move(ucd));
with the following output:
UncopyableDataStore test:
move assignment
and notice we now only have one move which is good.
The STL containers however need to be generic, they need to work with all types of classes and be as optimal as possible. And if you really needed a generic implementation of the data stores above it might look like this:
template<class D>
class GenericDataStore {
D data_;
public:
void setData(const D& data) { data_ = data; }
void setData(D&& data) { data_ = std::move(data); }
};
In this way we get the best possible performance whether we are using uncopyable or unmovable classes but we have to have at least two overloads of the setData
method which might introduce duplicate code. Usage:
std::cout << "GenericDataStore<Data> test:\n";
Data d3;
GenericDataStore<Data> gds;
gds.setData(d3);
std::cout << "GenericDataStore<UnmovableData> test:\n";
UnmovableData umd2;
GenericDataStore<UnmovableData> gds3;
gds3.setData(umd2);
std::cout << "GenericDataStore<UncopyableData> test:\n";
UncopyableData ucd2;
GenericDataStore<UncopyableData> gds2;
gds2.setData(std::move(ucd2));
Output:
GenericDataStore<Data> test:
copy assignment
GenericDataStore<UnmovableData> test:
copy assignment
GenericDataStore<UncopyableData> test:
move assignment
Live demo. Hope that helps.
Few reasons:
const value_type& val
you will force another copy. Passing it by reference (value_type&
) helps you do that.val
cannot be modified in any way. This is done so by making it a `const'val
cannot be modified in any way and the function declaration is guaranteeing that