如何通过制作副本从函数返回引用
How to return a refrence from a function with making copy
我有一个函数,如果key
存在于map
中,则返回value
,例如:
map<int,string> mymap;
//Assume there are some key value pair in above map
string & ReturnKey(int &a)
{
string ret;
map<int,string>::iterator iter = mymap.find(a);
if(iter not_eq mymap.end())
{
ret = iter->second;//I think this will make copy
}
else
return ret;
}
如何避免从上述函数返回的字符串副本?
如果你对
返回的引用是 const 感到满意,你可以做这样的事情:
const string & ReturnKey(int a)
{
static const string defaultValue; // to be returned if object isn't found
map<int,string>::iterator iter = mymap.find(a);
if(iter != mymap.end())
{
return iter->second;
}
else return defaultValue;
}
在未找到的情况下返回对 (defaultValue) 的引用是安全的,因为 defaultValue 被声明为静态,因此在函数返回后仍然存在。 在找到值的情况下,调用方需要注意不要持有引用,并在清除或修改 mymap 后尝试使用它,但这在实践中通常不是问题。
您可以返回对现有字符串的引用,如果它不存在,则可以引发异常。这可以通过std::map::at
方法轻松完成:
string& ReturnKey(int a)
{
return mymap.at(a);
}
如果您坚持使用C++11之前的编译器,则必须手动完成:
string& ReturnKey(int a)
{
map<int,string>::iterator iter = mymap.find(a);
if(iter == mymap.end())
throw std::out_of_range("Invalid key");
return iter->second;
}
与在程序中一样,您无法返回函数内声明的变量的引用,因为随着函数完成执行,该函数内声明的所有变量都将被释放和删除。
因此,在这种情况下,每次调用函数时,您都会得到null
或garbage value
。
为此,我认为您可以在函数中pass your string argument as a reference
。因此,通过使用它,您可以在变量中获得所需的值。
或 您还可以将函数的返回类型更改为 std::string
。
我认为您必须将此功能用作:
map<int,string> mymap;
//Assume there are some key value pair in above map
void ReturnKey(int &a, string& str)
{
map<int,string>::iterator iter = mymap.find(a);
if(iter not_eq mymap.end())
{
str = itr->second;
}
}
或者,您可以返回操作状态的std::string
值。如下:
map<int,string> mymap;
//Assume there are some key value pair in above map
std::string ReturnKey(int &a)
{
std::string ret;
map<int,string>::iterator iter = mymap.find(a);
if(iter not_eq mymap.end())
{
ret = iter->second;//I think this will make copy
}
else{
delete ret;
return null;
}
return ret;
}
并且应使用#include <string>
。
希望这对您有所帮助。
相关文章:
- 从函数返回const char*数组
- 检查函数返回类型是否与STL容器类型值相同
- 从 c 或 cpp 系列子函数返回到主函数
- 从函数返回任意简单类型的数据
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 从 C++ 中的函数返回数组地址问题
- VirtDisk.h QueryChangesVirtualDisk() 函数返回 RangeCount 为 0
- 为什么glGetSubroutineIndex为不同的函数返回相同的值?
- 在 c++ 中将函数返回类型指定为模板参数
- 从封装在对象中的函数 C++ 返回时为空的列表
- 为什么向量内部的指针在从函数返回时会发生变化?
- 函数返回的 rvalue 引用(表达式)是 xvalue - 但没有标识?
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 寿命延长从函数返回引用
- 程序不向函数返回值
- 字符串函数返回奇怪的值
- 类的大问题,以及从空函数c++返回
- 为什么在尝试测量函数返回所需的时间时,我的运行时编号是错误的?
- C++二叉搜索树模板从函数返回节点
- NVCC 错误:string_view.h:constexpr 函数返回是非常量