There are two vectors std :: vector and QVector. We have to check how “shift” elements when inserted. (Is constructed two vectors with the five elements and inserted zero element) I’ve this code:
#include <QVector>
#include <QTextStream>
struct MoveTest
{
int i;
MoveTest() {}
MoveTest(const MoveTest& other) {QTextStream(stdout) << "constr copy" << endl;}
MoveTest(MoveTest &&other) {QTextStream(stdout) << "constr move" << endl;}
~MoveTest() {}
inline MoveTest& operator= (const MoveTest& other) {QTextStream(stdout) << "copy" << endl;}
inline MoveTest& operator= (MoveTest &&other) {QTextStream(stdout) << "move" << endl;}
};
int main(int argc, char *argv[])
{
QTextStream(stdout) << "std::move:" << endl;
MoveTest t1;
MoveTest t2(std::move(t1));
t1 = std::move(t2);
QTextStream(stdout) << "QVector:" << endl;
QVector<MoveTest> qmTest(5);
qmTest.insert(qmTest.begin(), MoveTest());
QTextStream(stdout) << "std::vector:" << endl;
std::vector<MoveTest> mTest(5);
mTest.insert(mTest.begin(), MoveTest());
return 0;
}
My output with gcc 4.7.2, QMAKE_CXXFLAGS += -std=c++0x:
std::move:
constr move
move
QVector:
constr copy
constr copy
constr copy
constr copy
constr copy
constr copy
copy
copy
copy
copy
copy
copy
std::vector:
constr move
constr copy
constr copy
constr copy
constr copy
constr copy
How to insert elements with an internal shift without copying? What GCC flags are needed?
Since your move operator can throw an exception,
std::vectorcan’t use it. What would it do if the operator threw an exception halfway through the resize process? Declare it noexcept if it cannot throw an exception and the the vector implementation can use it.