【问题标题】:Calling inherited template constructor of unique_ptr subclass调用 unique_ptr 子类的继承模板构造函数
【发布时间】:2015-10-29 15:13:43
【问题描述】:

这不是模板构造函数甚至调用继承的模板构造函数的问题的重复。

它专门用于在 unique_ptr<...> 模板的类实例(?)的子类中调用继承的构造函数。

问题

为了让代码更容易理解,我在这个例子中使用了using

using B = std::unique_ptr<int *, decltype(&::free)>;

class int_ptr : public B {
    int_ptr(int *b) : B(b, &::free) { };
};

但编译失败:

In constructor 'int_ptr::int_ptr(int*)':
error: no matching function for call to 
    'std::unique_ptr<int*, void (*)(void*) throw ()>::unique_ptr(int*&, void (*)(void*) throw ())'

int_ptr(int *b) : B(b, &::free) { };
                              ^

我能想到的缺少功能匹配的唯一可能原因是存在throw (),但我不确定该怎么做,或者它是否是个问题。可能unique_ptr 是禁止抛出的。

否则,不匹配的函数正是我期望匹配的。


原因

我不想在每次声明 unique_ptr 的实例时都指定析构函数。这个答案https://stackoverflow.com/a/16615285/2332068 有一个很好的选择,但我很想知道我的尝试有什么问题。

当然,在现实生活中它不是int*,我试图用unique_ptr 包装,而是一些不透明的(但不是void*)指针。

我的意图是在范围退出时正确释放来自 C API 的所有这些指针。

也许我可以使用析构函数将这些指针约束到一个类/结构中,但我看不出它会节省多少。

结果

根据@RSahu 的提示,我想出了unique_dptr 来避免需要继续指定析构函数,但可以替代在std 命名空间中覆盖模板删除函数:

void free_int(int* p) {
  delete p;
}

template<typename T, void (*D)(T*)>
class unique_dptr : public std::unique_ptr<T, decltype(D)> {
    public: unique_dptr(T* t) : std::unique_ptr<T, decltype(D)>(t, D) { };
};

using int_ptr = unique_dptr<int, ::free_int>;
int_ptr i(new int(2));

【问题讨论】:

  • 我怀疑你需要使用using B = std::unique_ptr&lt;int, decltype(&amp;::free)&gt;;
  • @RSahu 这就是答案。
  • 有趣。但仅适用于using 子句。我之前已经将int* 的所有实例替换为int,但得到:error: invalid conversion from 'int' to 'std::unique_ptr&lt;int, void (*)(void*) throw ()&gt;::pointer {aka int*}' [-fpermissive] 我猜这是因为模板采用类型,但模板实例构造函数采用指针。 - 谢谢!请将其作为答案,以便我将您标记为回答者!

标签: c++ templates inheritance constructor


【解决方案1】:

std::unique&lt;int&gt;ints 的智能指针,即int* 的替代品。

使用std::unique&lt;int*&gt;时,指针需要为int**

代替

using B = std::unique_ptr<int *, decltype(&::free)>;

使用

using B = std::unique_ptr<int, decltype(&::free)>;

工作代码(谢谢,@CompuChip):http://ideone.com/ul29vr

【讨论】:

  • 证明:ideone.com/ul29vr。 (顺便说一句,您可能希望使该构造函数比私有的更易于访问。)
  • 我没有意识到模板需要一个类型,但是生成的构造函数却需要一个指向相同类型的指针。
猜你喜欢
  • 2019-12-14
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 2018-09-29
  • 2021-07-13
  • 1970-01-01
  • 2019-12-14
相关资源
最近更新 更多