簡體   English   中英

Qt5:如何擺脫此Singleton的編譯器警告?

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

我在Windows 7平台上使用Qt5。
我已經為我使用的數據庫實現了Singleton。
到目前為止,還可以,它可以正常工作,但是當我編譯代碼時,我總是收到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)基類QObject應該在復制構造函數中顯式初始化
2)函數中沒有返回非空值的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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM