簡體   English   中英

具有不可復制功能的接口

[英]Interface with non-copyable features

我正在嘗試實現一個日志工廠,並且我使用了一個接口,以便我可以隨時交換記錄器。

這是界面

class ILogger
{
public:

    //Only allow string input. The entire ARC is going to be non-unicode.
    virtual void log(std::string message, eLogLevel level=DEBUG) = 0;

protected:
    virtual ~ILogger(void){};


private:
    // No one can create an ILogger as it is abstract but should also
    // disallow copying... why copy a logger? Only one per file. Besides want to 
    // force people to use the factory.
    /*ILogger(const ILogger&);
    ILogger& operator=(const ILogger&);*/ // REMOVED THIS BECAUSE OF ERROR

};

這是一個派生的 class (標題)

class GenericLoggerImpl :
    public ILogger
{
public:
    virtual ~GenericLoggerImpl(void);
    virtual void log(std::string message, eLogLevel level=DEBUG);

private:
    GenericLoggerImpl(void); //USE THE FACTORY
    std::tr1::shared_ptr<GenericLogger> pImpl; //This is the implementation
    friend class LoggerFactory; // class LoggerFactory can now build these
};

和 CPP

GenericLoggerImpl::GenericLoggerImpl(void):pImpl()
{
    pImpl = std::tr1::shared_ptr<GenericLogger> (new GenericLogger()); //This is the implementation
}

GenericLoggerImpl::~GenericLoggerImpl(void)
{
}

void GenericLoggerImpl::log(std::string message, eLogLevel level)
{
    pImpl->logMsg(message.c_str(),level);
}

現在問題來了。 看到在ILogger界面中,我注釋掉了一段私有代碼嗎? 那是為了阻止任何人復制 ILogger 派生的 class (就像 boost::noncopyable 一樣)。 這很有意義(無論如何對我來說),因為它不允許單獨的記錄器實例訪問同一個文件,並通過我方便的 LoggerFactory 使用戶 go。

當包含這些行時,我收到以下錯誤:

genericloggerimpl.cpp(6): 錯誤 C2512: 'ILogger': 沒有合適的默認構造函數可用

那是關於什么的? 我不希望這些對象是可復制的。 我怎樣才能做到這一點?

任何用戶定義的構造函數(包括復制構造函數)的存在都會阻止編譯器生成默認構造函數。 您的子類GenericLogger依賴於ILogger的默認構造函數的存在(它被隱式調用,因為在GenericLogger的構造函數的初始化列表中沒有另行指定),因此出現錯誤。

要解決此問題,只需為ILogger聲明一個受保護的普通默認構造函數:

ILogger() {}

您可以從以下 class 繼承,以禁用要保護的任何 class 的復制:

class no_copy
{
protected:
    // For derived class. Protected just to avoid direct instantiation of this class
    no_copy(){}

private:    
    no_copy(const no_copy&);
    void operator =(const no_copy&);
};

例子:

class MyClass:public no_copy
{
};

錯誤:

MyClass cls1;
MyClass cls2(cls1); // Error
cls2 = cls1; // Error

暫無
暫無

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

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