gpt4 book ai didi

c++ - 在构造函数中使用 shared_from_this()

转载 作者:行者123 更新时间:2023-11-30 05:20:22 27 4
gpt4 key购买 nike

如您所知,不可能在对象的构造函数中使用 std::enable_shared_from_this 和 shared_from_this() 对,因为包含该类的 shared_pointer 尚不存在。但是,我真的很想要这个功能。我尝试了我自己的系统,它似乎工作正常。

namespace kp
{

template <class T>
void construct_deleter(T *t)
{
if(!t->_construct_pself)
{
t->~T();
}

free(t);
}

template <class T, typename... Params>
std::shared_ptr<T> make_shared(Params&&... args)
{
std::shared_ptr<T> rtn;
T *t = (T *)calloc(1, sizeof(T));
t->_construct_pself = &rtn;
rtn.reset(t, construct_deleter<T>);
t = new(t) T(std::forward<Params>(args)...);
t->_construct_pself = NULL;
t->_construct_self = rtn;

return rtn;
}

template <class T>
class enable_shared_from_this
{
public:
std::shared_ptr<T> *_construct_pself;
std::weak_ptr<T> _construct_self;

std::shared_ptr<T> shared_from_this()
{
if(_construct_pself)
{
return *_construct_pself;
}
else
{
return _construct_self.lock();
}
}
};

}

有人能发现这个逻辑中的任何缺陷吗?在构造函数调用之前,我基本上使用 placement new 将指针分配给类内的 shared_ptr。

就目前而言,我可以这样使用它:

std::shared_ptr<Employee> emp = kp::make_shared<Employee>("Karsten", 30);

在 Employee 构造函数中:

Employee::Employee(std::string name, int age)
{
Dept::addEmployee(shared_from_this());
}

在我将其提交到一个相对较大的代码库之前,我非常感谢你们的一些想法或反馈。

谢谢!

最佳答案

我知道这已经有一段时间了,但这可能对遇到同样问题的人有用:如果您尝试从继承您的 enable_shared_from_this 的类继承,则会发生主要问题。 .特别是这一行:

t->_construct_pself = &rtn;

如果你有让我们说:

class Object : public kp::enable_shared_from_this<Object> {
};

class Component : public Object {
};

那么编译器将无法转换 std::shared_ptr<Component>*std::shared_ptr<Object>*至于编译器,即使 Component 这些类型也不相关继承Object .我看到的最简单的解决方案是转 _construct_pselfvoid*像这样:

template <class T>
class enable_shared_from_this
{
public:
void* _construct_pself{ nullptr };
std::weak_ptr<T> _construct_self;
std::shared_ptr<T> shared_from_this() const
{
if (_construct_pself)
{
return *static_cast<std::shared_ptr<T>*>(_construct_pself);
}
else
{
return _construct_self.lock();
}
}
};

然后做

t->_construct_pself = static_cast<void*>(&rtn);

它不是很性感,可能会出现其他问题,但它似乎在工作......

[EDIT] 有一个稍微好一点、更“C++”的替代方案,很抱歉没有马上考虑它,只是做:

t->_construct_pself = reinterpret_cast<decltype(t->_construct_pself)>(&rtn);

[EDIT2] 制作 shared_from_this const 因为它不会改变类中的任何内容

[EDIT3] 发现另一个问题:如果您通过 make_shared 使用复制构造函数并使用 operator=shared_from_this 之前的构造函数中, shared_from_this将返回复制对象的地址,而不是对象拷贝的地址。我看到的唯一解决方案是为 enable_shared_from_this 定义空复制构造函数和赋值运算符并在每次需要时显式地从继承类中调用复制构造函数......或者确保你永远不会调用operator=之前shared_from_this在你的复制构造函数中。

关于c++ - 在构造函数中使用 shared_from_this(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40688090/

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