[英]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));
}
I get this warning from the returning value in the second function: 我从第二个函数的返回值中收到此警告:
returning reference to temporary [enabled by default]
返回对临时文件的引用[默认启用]
How to fix this? 如何解决这个问题? And I can't change the returning values of each function!
而且我无法更改每个函数的返回值!
You get the warning because getPart
returns a copy of song_parts[index]
. 您得到警告,因为
getPart
返回song_parts[index]
的副本 。 If it returns reference to song_parts[index]
, then your code would be correct. 如果它返回对
song_parts[index]
引用 ,那么您的代码将是正确的。
So you need to change the return type of getPart
to SongPart const&
: 因此,您需要将
getPart
的返回类型更改为SongPart const&
:
SongPart const & mtm::SongStructure::getPart(int index) const {
assert(index >= 0 && index < num_of_parts);
return song_parts[index];
}
The const
is necessary, as the function is a const
member function. const
是必需的,因为该函数是const
成员函数。
Why use assert
in operator[]
also when you forward the call to getPart
which does the assert anyway? 为什么要使用
assert
在operator[]
同时,当你呼叫转发到getPart
这确实断言呢? Just write this: 只需写下:
const SongPart& mtm::Song::operator[](int index) const {
//assert(index >= 0 && index < song_length); not needed!
return (song_format->getPart(index));
}
Avoid extra bound-checks when it is not needed. 避免在不需要时进行额外的边界检查。
change the first function to be: 将第一个函数更改为:
const SongPart& mtm::SongStructure::getPart(int index) const {
assert(index >= 0 && index < num_of_parts);
return song_parts[index];
}
the reason is the call to song_format->getPart(index)
returned by value, thus create a local on the stack of the 2nd function. 原因是通过值返回对
song_format->getPart(index)
的调用,因此在第二个函数的堆栈上创建了一个本地。 And if you return a reference to it, after the 2nd function returns, Boom.... 如果返回对它的引用,则在第二个函数返回后,Boom ....
If you cannot change the return type of getPart()
, then you cannot usefully invoke it. 如果您不能更改
getPart()
的返回类型,则无法有效地调用它。 Let's consider how you can access the data without invoking getPart()
. 让我们考虑一下如何在不调用
getPart()
情况下访问数据。
Solution 1: Call some other function: 解决方案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));
}
Solution #2: return song_parts[index]
directly from operator[]
: 解决方案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.