返回对临时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
成员函数。
为什么在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]);
}
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?