本文介绍了什么时候应该使用remove_reference和add_reference?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看[VC10的] unique_ptr,他们做了一些我不明白的事情:

I'm looking at [VC10's] unique_ptr and they do a couple things I don't understand:

typedef typename tr1::remove_reference<_Dx>::type _Dx_noref;

_Dx_noref& get_deleter()
    {   // return reference to deleter
    return (_Mydel);
    }

unique_ptr(pointer _Ptr,
    typename _If<tr1::is_reference<_Dx>::value, _Dx,
        const typename tr1::remove_reference<_Dx>::type&>::_Type _Dt)
    : _Mybase(_Ptr, _Dt)
    {   // construct with pointer and (maybe const) deleter&
    }

typename tr1::add_reference<_Ty>::type operator*() const
    {   // return reference to object
    return (*this->_Myptr);
    }

不只是写_Dx&或_Ty&

Wouldn't just writing _Dx& or _Ty& be the same thing?

我真的明白为什么他们这样做:

I actually do understand why they did it here though:

unique_ptr(pointer _Ptr, typename tr1::remove_reference<_Dx>::type&& _Dt)
    : _Mybase(_Ptr, _STD move(_Dt))
    {   // construct by moving deleter
    }


推荐答案

get_deleter



从返回类型中删除任何引用,然后添加引用。在符合的C ++ 11中,向现有的& (或)添加& &&&< / code>)会产生& 。然而,在C ++ 03中,这将形成对引用类型的引用,这是非法的。可能是MSVC正在使用旧的规则,或者代码是写的时候它是和保持因为它是无害的。

get_deleter

Any reference is removed from the return type, then a reference is added back. In conformant C++11, adding a & to an existing & (or &&) produces a &. In C++03 however, that would be forming a reference to reference type, which was illegal. Likely MSVC is using the old rules, or that code was written when it did and remains because it is harmless.

在这里,它们删除引用,添加 const ,然后添加引用返回,传递 const 参考。这是因为直接向引用类型添加 const 会导致无效 ! (§8.3.2/ 1)在C ++ 11或C ++ 03中,参数声明将是有效的,但如果引用aren,则不会添加 const 不会移除和替换。

Here they remove the reference, add const, and then add the reference back, to be passing by const reference. This is because adding const directly to a reference type does nothing! (§8.3.2/1) In either C++11 or C++03, the parameter declaration would be valid but would not add a const, if the reference weren't removed and replaced.

这本质上与 get_deleter 相同,但是它们以不同的方式,并且 _Ty 不能是引用键入开始。在我看来, _Ty& 就足够了,但这是他们的特权。

This is essentially the same as get_deleter, but they went about it a different way, and _Ty cannot be a reference type to begin with. It looks to me like _Ty& would suffice, but it's their prerogative.

这篇关于什么时候应该使用remove_reference和add_reference?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 08:40