簡體   English   中英

返回對臨時C ++的引用

[英]Returning reference to temporary c++

SongPart mtm::SongStructure::getPart(int index) const {
    assert(index >= 0 && index < num_of_parts);
    return song_parts[index];
}

const SongPart& mtm::Song::operator[](int index) const {
    assert(index >= 0 && index < song_length);
    return (song_format->getPart(index));
}

我從第二個函數的返回值中收到此警告:

返回對臨時文件的引用[默認啟用]

如何解決這個問題? 而且我無法更改每個函數的返回值!

您得到警告,因為getPart返回song_parts[index]副本 如果它返回對song_parts[index] 引用 ,那么您的代碼將是正確的。

因此,您需要將getPart的返回類型更改為SongPart const&

SongPart const & mtm::SongStructure::getPart(int index) const {
    assert(index >= 0 && index < num_of_parts);
    return song_parts[index];
}

const是必需的,因為該函數是const成員函數。

為什么要使用assertoperator[]同時,當你呼叫轉發到getPart這確實斷言呢? 只需寫下:

const SongPart& mtm::Song::operator[](int index) const {
    //assert(index >= 0 && index < song_length); not needed!
    return (song_format->getPart(index));
}

避免在不需要時進行額外的邊界檢查。

將第一個函數更改為:

const SongPart& mtm::SongStructure::getPart(int index) const {
    assert(index >= 0 && index < num_of_parts);
    return song_parts[index];
}

原因是通過值返回對song_format->getPart(index)的調用,因此在第二個函數的堆棧上創建了一個本地。 如果返回對它的引用,則在第二個函數返回后,Boom ....

如果您不能更改getPart()的返回類型,則無法有效地調用它。 讓我們考慮一下如何在不調用getPart()情況下訪問數據。

解決方案1:調用其他函數:

const SongPart& mtm::SongStructure::getPartReference(int index) const {
    assert(index >= 0 && index < num_of_parts);
    return song_parts[index];
}

const SongPart& mtm::Song::operator[](int index) const {
    assert(index >= 0 && index < song_length);
    return (song_format->getPartReference(index));
}

解決方案2:直接從operator[]返回song_parts[index] operator[]

const SongPart& mtm::Song::operator[](int index) const {
    assert(index >= 0 && index < song_length);
    return (song_format->song_parts[index]);
}

暫無
暫無

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

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