[Development] Don't use Private *d when your class is immutable

Olivier Goffart olivier at woboq.com
Fri Mar 3 13:37:36 CET 2017

On Freitag, 3. März 2017 12:19:42 CET Marc Mutz wrote:
> But don't - ever- use ref-counting on immutable classes. It's not easier
> (you need to implement all the special member functions, which peoole, me
> included[1][2], get wrong more often than we dare to admit).

refcounting is easy:

class FooBarPrivate;
class FooBar {
    QString someGetter();
    QString someOtherGetter();
    FooBar(QString something, QString somethingElse);

    const QSharedPointer<const FooBarPrivate> d;

And in the .cpp:
class FooBarPrivate { /*...*/ };

FooBar::FooBar(QString a, QString b) : 	
	d(QSharedPointer<FooBarPrivate>::create(std::move(a), std::move(b)));

What did i do wrong?
With QSharedPointer you can't go wrong, and you don't need to implement any 
special functions. And because the QSharedPointer keeps the deleter, you don't 
need the definition of FooBarPrivate to copy/move/destroy the class.
The overhead is 16 bytes (refcounts and deleter pointer).
Yet, I don't know so many classes that uses QSharedPointer internally.

Although it's good practice to still implement the special function out of 
line in the event in which we cant to add code in them in a future release. 
But that's actually quite unlikely.


Woboq - Qt services and support - https://woboq.com - https://code.woboq.org

More information about the Development mailing list