3

I'm coming from a C# background and still getting my head around c++ and Qt smart pointers. This should be a basic question:

In myClass.h

QSharedPointer<AccessFlags> m_flags;

In myClass.cpp I'm trying to set (is set the correct word?) the m_flags pointer

if(m_flags.isNull())
    m_flags = new AccessFlags();


class AccessFlags{
public:
     QHash<QString,int> flags;
     AccessFlags();  //The dictionary is setup in the constructor
};

The compiler complains "no match for 'operator=' in.. How do I set the pointer?

demonplus
  • 5,613
  • 12
  • 49
  • 68
DarwinIcesurfer
  • 1,073
  • 4
  • 25
  • 42

2 Answers2

6

You're trying to assign a raw pointer to a QSharedPointer in the line

m_flags = new AccessFlags();

You probably want something like

m_flags = QSharedPointer<AccessFlags>(new AccessFlags);
Fraser
  • 74,704
  • 20
  • 238
  • 215
5

Consider using std::shared_ptr instead QSharedPointer if you work with modern C++11 compiler (e.g. GCC 4.6 or above and MSVC 10.0).

First of all, it's a standard and second thing, you could use std::make_shared to init your pointer which can be faster! (For example, in MSVS2010/2012 allocation occurs only once for make_shared instead two allocations: one for new and one for internal counter).

Eugene Mamin
  • 749
  • 4
  • 8
  • 1
    There is a static `create` method, which makes the same as `std::make_shared`, so no gain here. And if the whole project uses QT classes, there is no reason to create a mess with standard classes and then have a pain converting one class objects to another. – rightaway717 May 05 '17 at 21:01
  • For the record: `create` method is only available in Qt5 – tobilocker Sep 25 '18 at 12:49