template <class ITEM> class Reference { private: ITEM *mRPointer ; public: inline Reference () { mRPointer = NULL ; } inline ~Reference () { if (mRPointer != NULL) { delete mRPointer ; mRPointer = NULL ; } } inline Reference (const Reference &right) { if (right.mRPointer == NULL) { mRPointer = NULL ; return ; } mRPointer = new ITEM (std::move (*right.mRPointer)) ; } inline Reference &operator= (const Reference &right) { if (this == &right) return *this ; this->~Reference () ; new (this) Reference (std::move (right)) ; return *this ; } inline Reference (Reference &&right) { mRPointer = right.mRPointer ; right.mRPointer = NULL ; } inline Reference &operator= (Reference &&right) { if (this == &right) return *this ; this->~Reference () ; new (this) Reference (std::move (right)) ; return *this ; } template <class _RET> inline operator _RET & () { return *mRPointer ; } template <class _RET> inline operator const _RET & () const { return *mRPointer ; } public: template <class... _ARGS> static Reference make (_ARGS &&...args) { TEMP<Reference> tmp ; Reference &r = _REFERENCE_CAST_<Reference> (tmp) ; r.mRPointer = new ITEM (std::forward<_ARGS> (args)...) ; return std::move (r) ; } } ;
想实现一个智能引用,但遇到一个问题
例如A类型能隐式转为int型的引用,那么Reference<A>也应该有这个特性
但不知道怎样实现,然后看网上用模板这样写
但是会有个问题例如const double &r = Reference<int> () ;
这样居然能编译,虽然编译器会提示返回临时变量地址
是原因是int能转化为double吗,所以引用绑定到*mRPointer隐式转换的右值上吗,那double &&r = Reference<int> () ;为什么就不行
问题是怎么阻止这样的隐式转换,或实现原来的需求
解决方案
10
inline Reference &operator= (const Reference &right) {
if (this == &right)
return *this ;
this->~Reference () ;
new (this) Reference (std::move (right)) ;
return *this ;
}
=============================
这些是垃圾代码
if (this == &right)
return *this ;
this->~Reference () ;
new (this) Reference (std::move (right)) ;
return *this ;
}
=============================
这些是垃圾代码
90
可以参考 std::reference_wrapper