View Full Version : Implicit sharing vs. c++ refereces
IrYoKu
23rd August 2007, 20:14
As I have understood from the QT docs, the advantages of the implicit sharing mechanism is that you can pass copy of objects as arguments without the need of copying large amounts of data (until you modify the contents). But aren't you able to obtain the same result by using standard c++ references (I mean the & in the arguments to functions)?
I am sure I am missing something, so if someone can explain, I would appreciate it a lot.
Thanks in advance,
Jorge
fullmetalcoder
23rd August 2007, 20:51
I am sure I am missing something, so if someone can explain, I would appreciate it a lot.
The next two samples may behave differently :
void MyClass::do(const QString& s)
{
m_string.clear();
// if s refers to m_string it now is empty...
}
void MyClass::do(QString s)
{
m_string.clear();
// even if m_string was passed to do(), s has kept its content
// because implicit sharing caused a fork of internal data
}
Implicit sharing is a way to ensure that sending a whole object is safer than sending a reference while not being expensive since the whole object is basically reduced to a pointer to internal (shared) data. It also avoid unneeded deep copy to occur. For instance :
QString s("some string");
QString s2 = s; // s2 and s share the same data hence reducing memory usage and avoiding to waste time copying the string, which could take a long time with a very long string...
IrYoKu
24th August 2007, 02:27
It's all crystal clear now, thanks =).
jpn
24th August 2007, 20:49
Implicit sharing can also have some significance in return values.
1) Not always you can return references. This means copying:
Value Object::getValue() const {
Value val; // a tmp variable you can't return a reference to
return val;
}
Value val = obj->getValue(); // val gets copied
2) Even if you can, you rarely see C++ code which properly assigns the returned reference. That's the only way to avoid copying:
const Value& Object::getValue() const {
return val; // for example a member variable
}
Value val1 = obj->getValue(); // val1 gets copied
const Value& val2 = obj->getValue(); // val2 doesn't get copied
This is where implicit sharing steps in. It does not only save CPU cycles 1) where using references is impossible but also 2) prevents common oversights of C++ programmers.
vBulletin® v3.7.1, Copyright ©2000-2008, Jelsoft Enterprises Ltd.