内部移动std :: vector元素和QVector

use*_*823 7 c++ qt gcc stl c++11

有两个向量std :: vectorQVector.我们必须检查插入时"移位"元素的方式.(用五个元素构造两个向量并插入零元素)我有这个代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的输出用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
Run Code Online (Sandbox Code Playgroud)

如何在不复制的情况下插入具有内部移位的元素?需要什么GCC标志?

Dav*_*rtz 5

由于您的move运算符可以抛出异常,std::vector因此无法使用它.如果操作员在调整大小过程中途抛出异常,它会怎么做?如果它不能抛出异常并且向量实现可以使用它,则声明它为noexcept.