Question

I'm dealing with QString, a implicit shared class of Qt. What I understand about implicit shared class is when copying the object, the actual data is not copy and just the pointer to the data is copied. It will only copy-on-write (when calling non-const functions). (Correct me if I'm wrong)

I want to know if the following code will be too expensive to used with implicit shared class:

// assume I have no control over those functions
QString giveMeAString();
void acceptStringReference(const QString &stringRef);

// I have control over this function
QString replaceSomething(QString input) { // shallow copy here
    input.replace("foo", "bar");          // deep copy here
    return input;                         // shallow copy here
}

// will this function expensive to call?
acceptStringReference(replaceSomething(giveMeAString());

Or should I use pointer? Does the function is much more expensive to call than passing a QString pointer like below (but more code)?

void replaceSomething(QString *input) {
    input.replace("foo", "bar");
}

QString *stringPtr = new QString(giveMeAString());
replaceSomething(stringPtr);
acceptStringReference(*stringPtr);
delete stringPtr;

3 more lines may looks less, but what if I need to call replaceSomething() many times?

Was it helpful?

Solution

Your first example is quite correct, copy-on-write will work well in this case.

The second example will work exactly like the first one. The only difference is that in the first case the temporary object returned by giveMeAString() is stored in the stack, and in the second case this object (stringPtr) is created explicitly in the heap. Dynamic allocating of small memory chunks is slow and pointless. The second example will be slower because of that. Internal handling of QString buffers will be exactly the same in both cases.

OTHER TIPS

How about this?

void replaceSomething(QString *input) {
    input->replace("foo", "bar");
}

QString string = giveMeAString();
replaceSomething(&string);
acceptStringReference(string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top