I’m writing a app for both linux & windows, and noticed that the GCC build is producing a lot of useless calls to the copy constructor.
Here’s an example code to produce this behavior:
struct A
{
A() { std::cout << "default" << std::endl; }
A(A&& rvalue) { std::cout << "move" << std::endl; }
A(const A& lvalue) { std::cout << "copy" << std::endl; }
A& operator =(A a) { std::cout << "assign" << std::endl; return *this; }
};
BOOST_AUTO_TEST_CASE(test_copy_semantics)
{
std::vector<A> vec_a( 3 );
}
This test just creates a vector of 3 elements. I expect 3 default constructor calls and 0 copies as there are no A lvalues.
In Visual C++ 2010, the output is:
default
move
default
move
default
move
In GCC 4.4.0 (MinGW), (-O2 -std=c++0x), the output is:
default
copy
copy
copy
What is going on and how do I fix it? Copies are expensive for the actual class, default construction and moves are cheap.
Both implementations (Visual C++ 2010 and GCC 4.4.0) are in error. The correct output is:
This is specified in 23.3.5.1 [vector.cons]/4:
Requires: T shall be DefaultConstructible.
The implementation is not allowed to assume that A is either MoveConstructible nor CopyConstructible.