
Originally Posted by
IrYoKu
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(const QString& s)
{
m_string.clear();
// if s refers to m_string it now is empty...
}
To copy to clipboard, switch view to plain text mode
{
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
}
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
}
To copy to clipboard, switch view to plain text mode
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 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...
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...
To copy to clipboard, switch view to plain text mode
Bookmarks