标准库容器在GCC的右值上产生大量副本 [英] Standard library containers producing a lot of copies on rvalues in GCC
问题描述
我正在为一个linux&窗口,并注意到GCC构建正在对复制构造函数产生大量无用的调用。
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 );
}
这个测试只是创建一个3个元素的向量。我期望3默认构造函数调用和0副本,因为没有 A
lvalues。
This test just creates a vector of 3 elements. I expect 3 default constructor calls and 0 copies as there are no A
lvalues.
在Visual C ++ 2010,输出为:
In Visual C++ 2010, the output is:
default
move
default
move
default
move
在GCC 4.4.0(MinGW),(-O2 -std = c ++ 0x),输出为:
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.
推荐答案
0)是错误的。正确的输出是:
Both implementations (Visual C++ 2010 and GCC 4.4.0) are in error. The correct output is:
default
default
default
这是在23.3.5.1 [vector.cons] / 4中指定的:
This is specified in 23.3.5.1 [vector.cons]/4:
:T应为DefaultConstructible。
Requires: T shall be DefaultConstructible.
实现不允许假定A是MoveConstructible或CopyConstructible。
The implementation is not allowed to assume that A is either MoveConstructible nor CopyConstructible.
这篇关于标准库容器在GCC的右值上产生大量副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!