Important: Please read the Qt Code of Conduct -

[SOLVED] Qt smart pointers and factory methods

  • I like Herb Sutter's advice ("blog post": to return an std::unique_ptr from factory methods. Using unique_ptr expresses the fact that the factory doesn't retain the object (if it was a shared_ptr, it wouldn't be clear that the factory didn't retain a reference) and it lets the caller take unique ownership of it. It's also safe if the caller does nothing with the return value - the unique_ptr will just go out of scope and deallocate the object.

    What would be the equivalent way of doing this using Qt's smart pointers? My first idea was to return a QScopedPointer from the factory, but that doesn't work, for the reason that - and please correct me if I've got this wrong - it doesn't have any notion of moving a reference, so it just disallows assignment.

    Edit: Other alternatives:

    • Return bare pointer: Says nothing about intended usage: should caller take ownership?
    • Return QSharedPointer: Again, doesn't communicate that the caller is supposed to own the object.

    If I don't receive any advice to do otherwise, I will probably return a QSharedPointer from my factory - after all I'm writing an application, not a framework - but it's not as clear as the std::unique_ptr version.

    Edit 2: Fixed link to Sutter's blog

  • There is nothing wrong with using std::unique_ptr within your Qt application. If unique_ptr is what you need, just use it. There is no rule that says that if you use Qt, every class, template or library that you use has to start with a Q...

  • Thanks for the answer!

    I've been hesitant to switch to std:: smart pointers in my code, since I've had a feeling that the Qt smart pointers play nicer with other fundamentals in Qt (QObject for instance) than the std:: ones. (I say feeling, because I don't have the time to read and understand Qt, so using Q* classes as far as possible feels safer).

    However, hearing this from a "Dinosaur Breeder" :-) gives me confidence to use std::unique_ptr and friends if I feel it fits my solution better.

    But still, just to keep learning: If anyone has thoughts on this, comments about how you use Qt's smart pointers in similar situations, it'd be interesting to hear about it.

    Thanks again!

  • There is no Qt equivalent, as that would really duplicate code. The current trend in Qt is to use more standaard Qt when possible, and to try and not do more duplication of (standard) stuff than really needed. The only smart pointer in Qt that is really Qt specific and interacts with other Qt classes (QObject, in fact) is QPointer. The others can be used with any type.

    /me used to be Mad Scientist here, by the way, but I don't have the time to keep up with the forum that much any more... ;)

Log in to reply