返回一个临时的引用 [英] returning a reference to temporary

查看:158
本文介绍了返回一个临时的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道返回一个临时的引用是非法的,但这里是我的问题:

I understand that it's illegal to return a reference to a temporary, but here's my problem:

const stringSet & Target::dirList( const dirType type ) const
{
    switch( type )
    {
        case SOURCE_DIR:
            return m_sourceDirs;
        case HEADER_DIR:
            return m_headerDirs;
        case RESOURCE_DIR:
            return m_resourceDirs;
        default:
            return stringSet(); // PROBLEM HERE!
    }
}

前三个选项返回一个const引用 stringSet 数据成员。我应该对默认情况做什么?如果我离开了,编译器(GCC的 -Wall -Wextra -pedantic )抱怨,我不想要,因为这些选项倾向于抓住我的床设计选择)

The three first three options return a const reference to a stringSet data member. What should I do for the default case? If I leave it out, the compiler (GCC with -Wall -Wextra -pedantic) complains and I don't want it to because those options tend to catch my bed design choices in the most odd of ways :)

谢谢!

推荐答案

保持默认设置为成员...并返回对它的引用。这当然是如果默认情况下理论上可能。如果不是,抛出异常,不返回任何东西。

Keep a default set as a member too... and return a reference to it. That is of course if the default case is theoretically possible. If it is not, throw an exception and don't return anything.

default:
   throw invalid_argument_exception();

这篇关于返回一个临时的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆