【问题标题】:Returning reference to temporary, const differences返回对临时常量差异的引用
【发布时间】:2013-04-18 22:51:14
【问题描述】:

当以下代码由 g++ 或 clang++ 编译时,我收到警告“返回对临时对象的引用”(g++) 和“返回对本地临时对象的引用”(clang++)。

有人能告诉我为什么getData_warning 会出现这些警告,而getData_nowarning 不会吗?

struct Geom {
    int * data;
};


// Not ideal because one can change the pointed to value
int * const & getData_nowarning (Geom const & geom) {
    return geom.data;
}


// Ideal because one cannot change the pointed to value.
int const * const & getData_warning (Geom const & geom) {
    return geom.data;    //   <-------------------  WARNING HERE
}


void test () {
    Geom const geom = { new int(0) };

    int * data1 = getData_nowarning(geom);

    int const * data2 = getData_warning(geom);
}

【问题讨论】:

    标签: c++ reference constants temporary


    【解决方案1】:

    因为geom.data的类型是int*,所以不能通过引用int const*来引用它。为了引用int const*,首先你需要一个int const*。所以必须有一个转换,所以必须创建一个新类型的新指针,所以它必须是一个临时的。

    您是否需要函数的调用者能够更改 geom 对象中的指针指向的内容?似乎不是,因为您正在使指针本身为 const。因此,只需删除引用,您就可以保留 const。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多