Qt5:如何消除这个Singleton的编译器警告

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

本文关键字:Singleton 编译器 警告 何消 Qt5      更新时间:2023-10-16

我在Windows7平台上使用Qt5
我已经为与我一起工作的数据库实现了Singleton
到目前为止还可以,它工作得很好,但当我编译代码时,我总是收到两个与复制构造函数和赋值运算符有关的警告。

这是代码:

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) 基类QObject应在复制构造函数中显式初始化
2) 函数中没有返回非void的return语句(用于赋值运算符代码行)。

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

  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;
    }
    

    警告是关于您忘记使用return *this;

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

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

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