gpt4 book ai didi

c++ - 带有破坏操作的侵入式引用计数

转载 作者:行者123 更新时间:2023-11-30 04:10:26 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com