开发者

Does QVector::replace() create a deep copy?

I have a memory leak in my application which I have been writing with Qt (C++) . And I suspect problem is with that line.

for(int i=0; i<DATA_LENGTH;i++){
        cdata1->replace(i,data->at(i));    
}

cda开发者_JAVA技巧ta1 is a QVector, data is a QList .

The reason I'm using replace(), I have constant length of data. And I didn't want to create a QVector each time. QVector is initialized on the object constructor with that line:

cdata1 = new QVector<double>(DATA_LENGTH,0);

Qt documentation says

Note that using non-const operators can cause QVector to do a deep copy.

What I'm asking does replace() function causes a deep copy or how can I understand that?


Deep copy means the whole container, not the elements. As linked just after the sentence you quoted, QVector uses implicit sharing, also known as copy-on-write. read-only copies of the container are cheap, as the internals are shared, until one of the copy is modified:

QVector<A> vec1;
...
QVector<A> vec2 = vec1; //cheap, only copies a pointer internally. vec1 and vec2
int siz2 = vec2.size();  //cheap, doesn't modify vec2, vec1 and vec2 are still the same object, internally
vec2[0] = something; //potentially expensive: modifies vec2, thus vec2 "detaches" from vec1, getting its own copy of vec1's internal data, which is then modified by the assignment.

That's also the reason why creating containers on the heap is rather nonsensical (and unidiomatic) in almost all cases and you should create them on the stack instead.


Yes, it copies your double values. But I don't think double values can be subject to Memory Leaks unless you create them with new?

Anyway, dependent on your surrounding code you can maybe replace that whole block by using

cdata1 = data->toVector();

(see http://doc.qt.nokia.com/latest/qlist.html#toVector)

As an additional hint, you should start using more readable variable names than cdata1 or data. Your variables should describe what they are storing, e.g. if you have a list storing temperature data points it should be called something like temperatureDataPoints or temperatureDataPointList. It involves more typing than "data" of course, but you won't regret using more readable names if you look at your code in a year or so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜