在C ++中将对临时参数的右值引用转换为const左值返回的正确方法

问题描述

我正在尝试实现类似find方法方法,以从容器中提取对值的引用,并在找不到该值或类型不兼容的情况下返回认值。

template<class T> const T& get (key_type k,const T& def)
{
    const T* r = dynamic_cast<const T*> (find(k)); // suppose `find` returns a pointer to common base class or NULL if the key not found
    return r ? *r : def; 
}

如果def是临时对象,则此函数无法正常工作:

const sometype& val = find(key,sometype(someargs));

那么,是否可以使用右值引用并以某种方式移动或复制临时对象来处理这种情况?

template<class T> const T& get (key_type k,T&& def)
{
    const T* r = dynamic_cast<const T*> (find(k)); // suppose `find` returns a pointer to common base class or NULL if the key not found
    return r ? *r : std::move(def); // or copy? or something else?
}

T也可能是抽象的基类。而且,请选择无助推解决方案。

解决方法

不,您不能。临时对象仅对该语句有效,在您通过返回的引用访问它之前,该临时对象将被销毁。

const sometype &val = get(not_existing_key,get_temporary_object());
do_something_with(val);

do_something_with(val)绑定到引用val的对象已被销毁。 get函数不应使用参数def的临时对象来调用。 相反,您可以将临时对象复制到变量,然后使用对该变量的引用来调用该函数。

auto copied_object = get_temporary_object();
const sometype &val = get(not_existing_key,copied_object);
do_something_with(val);

现在,绑定val的对象位于变量copied_object中。