How to create a deep copy of QList (Qt 4.8)

I am trying to make a deep copy of QList, I am using Qt 4.8. In the code below mDatathere is a member variable of the QList<unsigned char>class Test.

In the first case, I thought that the code below should work, however diving deeper into Qt is implicitly shared (i.e. copying to write), I doubt that this is the right way.

Test::Test(QList<unsigned char> &aData) {
    mData.QList(aData);
}

According to Qt,

QList :: QList (const QList and others)

Creates a copy of another.

This operation takes constant time because the QList is implicitly generic. This very quickly returns a QList from a function. If the shared instance is modified, it will be copied (copy-on-write) and which takes linear time.

, aData aData, mData. , ?

: Qt 4.5 - QList:: QList (const QList &) - ?, " , - .

+4
1

Qt QList, .

QList<int> a;
a.append(1);
a.append(2);

a .

QList<int> b = a;
// a = 1, 2
// b = 1, 2

b a. , , b .

b.append(3);
// a = 1, 2
// b = 1, 2, 3

:

QList<int> a;
a << 1 << 2 << 3;
// a = 1, 2, 3
QList<int> b = a;
// a = 1, 2, 3; b = 1, 2, 3
b[0] = 7;
// a = 1, 2, 3; b = 7, 2, 3

- b, . , , .

, , :

void addElement(QList<int> &x, int e) {
    x.append(e);
}

QList<int> a;
a.append(1);
a.append(2);
addElement(a, 3);
// a = 1, 2, 3

, . , , , .

void printListPlus1(QList<int> &x) {
    QList<int> xCopy = x; 
    xCopy.append(1);
    // print the list
}

QList<int> a;
a << 1 << 2;
// a = 1, 2
printListPlus1(a);
// a = 1, 2

, QList Qt, , int QString. "background".

, :

class Test {
    QList<int> _m;
public:
    Test(QList<int> m) : _m(m) {
    }    
}

Test m. - m , . .

, const:

class Test {
    QList<int> _m;
public:
    Test(const QList<int> &m) : _m(m) {
    }    
}

.

+5

All Articles