簡體   English   中英

為什么 g++ 會警告返回對臨時對象的引用

[英]Why does g++ warn about returning a reference to a temporary

我有以下代碼:

constexpr const_reference_t at(size_t p_pos) const
{
    using namespace std;

    return (p_pos > m_size)
        ? throw out_of_range{ string{ "string_view_t::at: pos > size() with pos = " } + to_string(p_pos) }
        : m_begin_ptr[p_pos];
}

編譯時,g++ 告訴我:

/home/martin/Projekte/pluto/pluto-lib/stringview.hpp:50: 警告:返回對臨時 [-Wreturn-local-addr] 的引用:m_begin_ptr[p_pos]; ^ m_begin_ptr 是:

const_pointer_t m_begin_ptr = nullptr;

而 const_pointer_t 的類型是 const char*

這段代碼是真的不正確還是錯誤的警告? 如果 g++ 是正確的,那為什么這是一個臨時的呢? 最后,我怎么能避免這個警告。

g++ 版本是 7.2.0

我進一步最小化了代碼:

static const char* greeting = "hallo, world!";

const char& nth(unsigned n)
{
    return true ? throw "" : greeting[n];
}

int main()
{
    return 0;
}

(p_pos > m_size)條件為true ,返回由throw創建的對象,根據文檔創建臨時對象。

異常對象是由 throw 表達式構造的未指定存儲中的臨時對象。

因為函數返回類型是const char& ,它是引用,編譯器試圖將臨時對象轉換為引用,所以你會收到警告。

你不應該試圖返回throw結果,你只是throw

我個人將三元運算符部分更改為:

if (p_pos > m_size) {
    // throw
}
return m_begin_ptr[p_pos];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM