5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

QList で生データをとってはいけない

Posted at

今日これにだいぶ時間を取られてしまったので備忘録としてとっておく

この中で唯一意図しない挙動を起こすものはどれだろうか?

    // 各種コンテナから int の配列にコピーする処理を実装するテスト
    quint32 stack[3];

    // QList 
    QList<int> list;
    list << std::numeric_limits<quint8>::max()
         << std::numeric_limits<quint16>::max()
         << std::numeric_limits<quint32>::max();
    memcpy(&stack[0], &list[0], sizeof(stack));
    qDebug() << stack[0] << stack[1] << stack[2];

    // QVector
    QVector<int> vector;
    vector << std::numeric_limits<quint8>::max()
           << std::numeric_limits<quint16>::max()
           << std::numeric_limits<quint32>::max();
    memcpy(&stack[0], &vector[0], sizeof(stack));
    qDebug() << stack[0] << stack[1] << stack[2];

    // std::vector
    std::vector<int> sv;
    sv.push_back(std::numeric_limits<quint8>::max());
    sv.push_back(std::numeric_limits<quint16>::max());
    sv.push_back(std::numeric_limits<quint32>::max());
    memcpy(&stack[0], &sv[0], sizeof(stack));
    qDebug() << stack[0] << stack[1] << stack[2];

    // QVarLengthArray
    QVarLengthArray<int> va;
    va.append(std::numeric_limits<quint8>::max());
    va.append(std::numeric_limits<quint16>::max());
    va.append(std::numeric_limits<quint32>::max());
    memcpy(&stack[0], &va[0], sizeof(stack));
    qDebug() << stack[0] << stack[1] << stack[2];

答えは QList で、実行する度に値が変化する。よって、配列内の生データを直接取得したい場合は QList 以外のコンテナを使うこと。

QList と QVector はよく似ているが、使用するアルゴリズムが異なる(一番の違いは QList は prepend がおおよそ O(1) で完結する点)。Qt 的には前者を推奨している。
http://qt-project.org/doc/qt-4.8/qvector.html
http://qt-project.org/doc/qt-4.8/containers.html#algorithmic-complexity

5
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?