我有一个 function address_of
,它返回 a Pointer
(封装 a shared_ptr
)到它的参数。address_of
需要同时处理左值和右值,因此有两个版本address_of
:一个接受引用,另一个接受右值引用。由于获取临时地址是一件坏事™,因此右值版本address_of
需要执行移动构造才能Pointer
真正拥有某些东西。实现很简单:
template<class T>
inline Pointer address_of(T& value) {
return Pointer(&value);
}
template<class T>
inline Pointer address_of(T&& value) {
return Pointer(new T(std::move(value)));
}
并按预期获取临时作品的地址:
Pointer p = address_of(Derived());
但是当我使用以下代码进行测试时:
Base* object = new Derived();
Pointer p = address_of(*object);
GCC 抱怨调用address_of
不明确:
error: call of overloaded ‘address_of(Base&)’ is ambiguous
note: candidates are: Pointer address_of(T&) [with T = Base]
note: Pointer address_of(T&&) [with T = Base&]
我的印象是一元*
总是返回一个左值,在这种情况下甚至不应该考虑右值版本。这里到底发生了什么?