作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 mixin 类,它使类引用计数,如下所示:
template<class D>
class ref_count_base
{
protected:
ref_count_base();
ref_count_base(ref_count_base const& x);
ref_count_base(ref_count_base&& x);
ref_count_base& operator=(ref_count_base const& x) &;
ref_count_base& operator=(ref_count_base&& x) &;
~ref_count_base();
private:
int* refs_;
};
// omitted constructors...
template<class D>
ref_count_base<D>::~ref_count_base()
{
if (!refs_)
return;
if (1 == *refs_) {
// C-style cast rather than static_cast allows us to call a member
// function in the derived class even if we are a private base.
((D*)this)->last_ref_released();
delete refs_;
} else {
--*refs_;
}
}
然后像这样使用这个类:
class program : private ref_count_base<program>
{
private:
void last_ref_released()
{
glDeleteProgram(name_);
}
private:
GLuint name_;
friend ref_count_base;
};
显然这行不通,因为 program
当我们到达 mixin 的析构函数时不再存在,所以我们不能调用 last_ref_released
在派生类中,但是否有类似的方法来实现这一点(最好不向派生类添加噪音)?
编辑:这是客户端代码的示例:
class entity
{
private:
// some other data members...
program prog_;
};
std::vector<entity> entities_;
for (auto& i : entities_) {
//i.bind_program();
glUseProgram(i.get_program_name());
// drawing code here...
}
请注意 shared_ptr<program>
而不是 program
这看起来喜欢glUseProgram(i->get_program_name())
.
最佳答案
编辑:令人困惑的是您没有尝试引用计数 program
类,但要引用 name_
的拷贝计数具有相同的值。
鉴于此,创建与 shared_ptr
具有相似语义的内容似乎更清晰, 但对于值类型...我们称之为 shared_value
:
template <typename T, void (*Deleter)(T)>
struct shared_value {
typedef shared_value<T,Deleter> Self;
// whatever ctors, assignment operators etc. you need here:
shared_value(Self const &other)
: value_(other.value_), refs_(other.refs_) {
++*refs_;
}
~shared_value() {
if (resf_) {
if (*refs_ == 1) {
Deleter(value_);
delete refs_;
}
else
--*refs_;
}
}
operator T& () { return value_; }
operator T const& () const { return value_; }
private:
T value_;
mutable int *refs_;
};
并像这样使用它:
class program {
shared_value<GLuint, glDeleteProgram> name_;
};
您可以在此处使用多态删除器增加灵 active - 我刚刚展示了最适合您的东西。
有一种简单的方法可以做您想做的事,而无需使用 CRTP 或 mixins 或根本不接触程序类。简单地写成这样:
class program {
GLuint name_;
public:
~program() {
glDeleteProgram(name_);
}
};
然后使用 std::shared_ptr<program>
你目前使用的任何地方program
(也就是说,只创建一个实例,然后将共享指针传递给它)。
如果你没有 std::shared_ptr
然而,使用 boost::shared_ptr
相反。
关于c++ - 带有破坏操作的侵入式引用计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20630189/
我是一名优秀的程序员,十分优秀!