gpt4 book ai didi

c++ - 返回对临时 C++ 的引用

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:16 25 4
gpt4 key购买 nike

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

我从第二个函数的返回值中得到这个警告:

returning reference to temporary [enabled by default]

如何解决这个问题?而且我无法更改每个函数的返回值!

最佳答案

您收到警告是因为 getPart 返回 song_parts[index]拷贝。如果它返回 referencesong_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 成员函数。

当您将调用转发给 getPart 时,为什么还要在 operator[] 中使用 assert 呢?只需这样写:

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

避免在不需要时进行额外的边界检查。

关于c++ - 返回对临时 C++ 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14407669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com