我有一个在线程之间传递的数据类。我希望这个类是一个仅std::shared_ptr
的类,不能通过从外部调用其析构函数来销毁,所以我也希望析构函数是私有的。我当前的解决方案是
template<typename T>
struct DestructorHelper
{
static void Destroy(void* v) { delete static_cast<T*>(v); }
};
class SharedOnly
{
public:
SharedOnly(const SharedOnly& other) = delete; // deleted copy constructor
SharedOnly& operator=(const SharedOnly& other) = delete; // deleted copy assignment operator
SharedOnly(SharedOnly&& other) = delete; // deleted move constructor
SharedOnly& operator=(SharedOnly&& other) = delete; // deleted move assignment operator
static std::shared_ptr<SharedOnly> create()
{
auto objPtr = new SharedOnly;
auto desPtr = &DestructorHelper<SharedOnly>::Destroy;
std::shared_ptr<SharedOnly> shared(objPtr, desPtr);
return shared;
}
private:
SharedOnly() = default;
~SharedOnly() = default;
friend struct DestructorHelper<SharedOnly>;
};
如果没有DestructorHelper
,我有办法上这堂课吗?我正在寻找的是一个优雅的解决方案,使std::shared_ptr
仅类,以便它可以传递给不同的线程,只有在最后一个共享指针指向对象被销毁时才被销毁。
您可以使用lambda来解析create
内部的析构函数访问:
static std::shared_ptr<SharedOnly> create()
{
return {new SharedOnly, [](SharedOnly *const s) { delete s; }};
}
当您使用share_ptr时,也就是说,您已经使用c++11或更高版本,您可以将DestructorHelper放在lambda函数中。
class SharedOnly
{
public:
SharedOnly(const SharedOnly& other) = delete; // deleted copy constructor
SharedOnly& operator=(const SharedOnly& other) = delete; // deleted copy assignment operator
SharedOnly(SharedOnly&& other) = delete; // deleted move constructor
SharedOnly& operator=(SharedOnly&& other) = delete; // deleted move assignment operator
static std::shared_ptr<SharedOnly> create()
{
auto objPtr = new SharedOnly;
std::shared_ptr<SharedOnly> shared(objPtr, [](SharedOnly *ptr) {
delete ptr;
});
return shared;
}
private:
SharedOnly() = default;
~SharedOnly() = default;
};