我目前正在使用智能指针编写一些代码,其中在许多点上有必要将这些指针强制转换为其基本类型并将它们作为 const 参数传递给函数。目前我正在使用shared_ptr和标准指针转换函数来实现这一点,但这似乎效率低下(因为每次转换至少需要一个CAS)并且还具有误导性(因为我们没有建模共享关系,父级是唯一的所有者)物体)。
因此,我想出了以下内容,但想检查它确实安全,还是有一些边缘情况会破坏它?
template <typename ToType, typename FromType>
class FTScopedCastWrapper {
public:
explicit FTScopedCastWrapper(std::unique_ptr<FromType>& p) : from_ptr_(&p) {
auto d = static_cast<ToType *>(p.release());
to_ptr_ = std::unique_ptr<ToType>(d);
}
~FTScopedCastWrapper() {
auto d = static_cast<FromType *>(to_ptr_.release());
(*from_ptr_) = std::unique_ptr<FromType>(d);
}
const std::unique_ptr<ToType>& operator()() {
return to_ptr_;
}
// Prevent allocation on the heap
void* operator new(size_t) = delete;
void* operator new(size_t, void*) = delete;
void* operator new[](size_t) = delete;
void* operator new[](size_t, void*) = delete;
private:
std::unique_ptr<FromType>* from_ptr_;
std::unique_ptr<ToType> to_ptr_;
}; …Run Code Online (Sandbox Code Playgroud)