返回对临时c++的引用

Returning reference to temporary c++

本文关键字:引用 c++ 返回      更新时间:2023-10-16
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成员函数。

为什么在operator[]中也使用assert,当你将调用转发给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)返回的值,从而在第二个函数的堆栈上创建一个局部。如果你返回对它的引用,在第二个函数返回后,嘣....

如果不能更改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]:

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