Y.H.
Y.H.

Reputation: 2847

Qt implicitly-shared container of explicitly-shared item

I created a class Foo that is explicitly shared. In my program I have a data member QVector<Foo> data; that I pass around between different classes by reference to optimize memory usage.

During runtime, an object might change a specific element of data. For example:

Foo item = data.at(0);
item.setName("newName");

I would like to know if a new vector is deeply copied because of a COW or is it just that Foo object at location 0 changed its name only?

Upvotes: 0

Views: 143

Answers (1)

Samuel Harmer
Samuel Harmer

Reputation: 4412

In your example item contains a copy of the Foo item at position 0 in data. This is because QVector::at() returns a const reference and the = says to copy it into item.

If you had:

Foo & item = data[0];
item.setName("newName"); // <--- typo of single quotes here in your version

The Foo item at position 0 in the QVector would now have the name "newName" because in this example, item is a reference and the QVector operators [] return a non-const reference to the actual Foo.

Upvotes: 1

Related Questions