问题描述
以下是尝试使用 operator ==
的修改语义实现共享指针:
The following is an attempt at implementing a shared pointer with a modified semantics of operator==
:
template <typename T>
struct deref_shared_ptr: private std::shared_ptr<T> {
using Base = std::shared_ptr<T>;
// ... using statements to include functionality from the base.
bool operator==(const deref_shared_ptr rhs) const {
return (**this == *rhs);
}
};
我正在努力实现一个等效的 std :: make_shared
这种类型。这是我的尝试:
I am struggling with implementing an equivalent of std::make_shared
for this type. This is my attempt:
template< class T, class... Args >
deref_shared_ptr<T> make_deref_shared( Args&&... args ) {
return reinterpret_cast<deref_shared_ptr<T>>(std::make_shared<T>(args...));
}
这不起作用:编译器( g ++ 5.4 .0
)投诉无效投射。为什么它不工作,我应该做什么,而不是这个演员?
This does not work: the compiler (g++ 5.4.0
) complains about an invalid cast. Why does it not work and what should I do instead of this cast?
推荐答案
您看到此编译器错误消息,因为 reinterpret_cast
通过私人继承。请检查以下主题有关此主题:,。
You see this compiler error message because the reinterpret_cast
cannot make casts through the private inheritance. Please check the following themes on this topic: difference between c++ casts, conversion which may be handled by c-style cast only.
只有通过 private
继承是c风格的转换。因此,更改您的示例如下使您的示例工作:
The only way to go through the private
inheritance is the c-style cast. So, changing your example as follows makes your example work:
template< class T, class... Args >
deref_shared_ptr<T> make_deref_shared(Args&&... args) {
return (deref_shared_ptr<T>)(std::make_shared<T>(args...));
}
c风格的转换在一般情况下是不安全的,因为它可能工作不正确的情况下多重遗产和一些其他情况下,但AFAIK它是安全的在这种情况下。
The c-style cast is not safe in the general case since it may work incorrectly in cases of multiple inheritance and some other cases, but AFAIK it's safe in this case.
这篇关于如何转换为私下派生的子类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!