0
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));
}

2 番目の関数の戻り値からこの警告が表示されます。

一時的な参照を返す [デフォルトで有効]

これを修正する方法は?そして、各関数の戻り値を変更することはできません!

4

3 に答える 3

4

のコピー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メンバー関数であるため、が必要です。

とにかくアサートする呼び出しを転送するときassertにも使用するのはなぜですか?これを書いてください:operator[]getPart

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

不要な場合は、余分な境界チェックを避けてください。

于 2013-01-18T21:19:21.833 に答える
2

最初の関数を次のように変更します。

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

その理由は、値によって返される呼び出しであるためsong_format->getPart(index)、2番目の関数のスタックにローカルを作成します。そして、それへの参照を返すと、2番目の関数が戻った後、Boom...。

于 2013-01-18T21:18:18.790 に答える
1

の戻り値の型を変更できない場合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:song_parts[index]から直接戻るoperator[]:

const SongPart& mtm::Song::operator[](int index) const {
    assert(index >= 0 && index < song_length);
    return (song_format->song_parts[index]);
}
于 2013-01-18T21:25:09.257 に答える