如何通过制作副本从函数返回引用

How to return a refrence from a function with making copy

本文关键字:函数 返回 引用 副本 何通过      更新时间:2023-10-16

我有一个函数,如果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;
}

与在程序中一样,您无法返回函数内声明的变量的引用,因为随着函数完成执行,该函数内声明的所有变量都将被释放和删除。

因此,在这种情况下,每次调用函数时,您都会得到nullgarbage 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>

希望这对您有所帮助。