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
 
                    


![[小白求帮助]分配的内存什么时候需要手动释放](https://www.codebye.com/wp-content/themes/douth/timthumb.php?src=https://www.codebye.com/wp-content/themes/douth/assets/img/pic/1.jpg&h=110&w=185&q=90&zc=1&ct=1)