Qt5:如何消除此 Singleton 的编译器警告?

Qt5: How to get rid of the compiler warnings for this Singleton?

我在 Windows 7 平台上使用 Qt5。
我已经为我使用的数据库实现了一个单例。
到目前为止没问题,它工作正常,但是当我编译代码时,我总是收到 2 个与复制构造函数和赋值运算符相关的警告。

代码如下:

class DataBase : public QObject
{
    Q_OBJECT

public:
    static DataBase * instance(QObject * parent = 0);
    static void destroy();
    //
    QString openDataBaseConnection();
    void closeDataBaseConnection(QString & connectionName);

private:
    DataBase(QObject * parent);
    ~DataBase();
    DataBase(DataBase const &){} // <- copy constructor
    DataBase & operator = (DataBase const &){} // <- assignment operator
    static DataBase * pInstance;
};

这里是编译器警告:

1) Base class QObject should be explicitly initialized in the copy constructor
2) No return statement in function returning non-void (that's for the assignment operator code line).

那么,我该怎么做才能最终摆脱这 2 个警告?

  1. 尝试使用与 other 相同的父代初始化 QObject 基:

    DataBase(DataBase const& other) :
    QObject(other.parent())
    // copy-construct members
    {
    } 
    
  2. operator= 应如下所示:

    DataBase &operator=(DataBase const& other)
    {
        QObject::operator=(other);
        // copy-assign members
        return *this;
    }
    

    警告是关于 you forgot to return *this;.

请注意,您所做的不是默认实现。他们什么都不做!

您可能希望使用 default 关键字(如果您在 C++11 或更高版本下编译)将这些函数的实现留给编译器:

DataBase(DataBase const &) = default;
DataBase &operator=(DataBase const&) = default;