c++ - 无法返回派生类型的 std::unique_ptr<>

标签 c++ inheritance unique-ptr

我有以下模板函数:

template<typename T = CRecordset>
std::unique_ptr<T> ExecuteSqlQuery(LPCTSTR pszSqlQuery = nullptr, RecordsetMode nMode = RecordsetMode::read)
{
    ASSERT(m_Database.IsOpen());
    std::unique_ptr<ITableRecordset> prs = std::make_unique<T>(&m_Database);
    if (!ExecuteSqlQuery(prs.get(), pszSqlQuery, nMode))
        prs.reset();
    return prs;
}

我这样调用它:

auto prs = db.ExecuteSqlQuery<CCustomerRecordset>(nullptr, RecordsetMode::bulkRead);

CCustomerRecordset源自 CTableRecordset<> , 和 CTableRecordset<>源自 ITableRecordset .

但是函数中的return语句报错:

Error C2440 'return': cannot convert from std::unique_ptr<ITableRecordset,std::default_delete<_Ty>>' to 'std::unique_ptr<CCustomerRecordset,std::default_delete<_Ty>>'  
    with  
    [  
        _Ty=ITableRecordset  
    ]  
    and  
    [  
        _Ty=CCustomerRecordset  
    ]

CCustomerRecordsetITableRecordset 的一种,为什么我不能这样做?

最佳答案

您的示例简化为:

struct A {};
struct B : A {};

A *a = new B;
B *b = a;

return 语句试图返回 unique_ptr<ITableRecordset>其中一个 unique_ptr<CCustomerRecordset>是期待。这是一个沮丧,不会隐含地发生。修复它的一种方法是在整个函数模板中充分利用具体类型。所以不是转换为接口(interface):

auto prs = std::make_unique<T>(&m_Database); 

关于c++ - 无法返回派生类型的 std::unique_ptr<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743280/

相关文章:

php - php抽象方法中的动态参数

c++ - 删除 unique_ptr 指向的内容

64位机器上的c++指针

c++ - 有人可以解释这个继承代码吗?

c++ - 在 Unix 上重定向标准输出

c# - 为多个 getter 执行的公共(public)操作

java - 多态性,我的程序的问题

c++ - 从 C++ 到 C 释放 unique_ptr 时如何避免内存泄漏

c++ - 通过函数创建 unique_ptr

c++ - Qt4应用程序崩溃,单击连接按钮时出现段错误