c++ - 在工厂中返回 unique_ptr

标签 c++ factory-pattern unique-ptr

也许这是一个简单的问题,因为我对 C++ 还是个新手。我想使用某种工厂来封装我的应用程序中的日志记录。这个想法是只有工厂知道哪个具体类将处理函数调用。应用程序将始终调用基本日志记录类的抽象接口(interface)。

工厂方法应该是这样的:

std::unique_ptr<AbstractLoggingClass> Factory::getDefaultLogger(const std::string& param){
    return new ConcreteLoggingClass(param);
}

ConcreteLoggingClassAbstractLoggingClass 的子类。

但是我得到以下错误:

Error: could not convert '(operator new(64ul), (<statement>,
((ConcreteLoggingClass*)<anonymous>)))' from 'ConcreteLoggingClass*'
to 'std::unique_ptr<AbstractLoggingClass>'

我的问题是我不知道如何实例化 ConcreteLoggingClass 并将 unique_ptr 返回给 AbstractLoggingClass

我已经找到了this post ,但我仍然没有看到解决方案。

最佳答案

你想要的 std::unique_ptr 构造函数是 explicit ,因此你需要......好吧......明确说明它。尝试

return std::unique_ptr<AbstractLoggingClass>(new ConcreteLoggingClass(param));

关于c++ - 在工厂中返回 unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34397430/

相关文章:

c++ - 指针的默认析构函数?

c++ - 我想做一个 'if' 声明,如果变量小于 80 t=0 但如果变量大于 t=x-80

c++ - 如何在C++中将输入输入到字符指针中

php - 工厂对象创建需要其他对象的对象

C++通用抽象工厂设计问题

c++ - unique_ptr、nullptr 并支持 gcc 4.5.x 和 4.6.x

c++ - 唯一_Ptr : Attemting To Reference A Deleted Function

c++ - 使用 OpenMP 和 Magick++ 进行逐像素图像处理

c# - 弱引用或工厂模式

c++ - 无法访问私有(private)成员 - 模板和 std::unique_ptr