繁体   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