繁体   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