函数,该函数返回一个字符串引用c++

Function that returns an string refrence c++

本文关键字:函数 一个 字符串 引用 c++ 返回      更新时间:2023-10-16

我对c++中的指针和引用很陌生,所以我想知道是否有人能给我一个例子,告诉我如何编写一个返回字符串引用的函数,也许还有正在使用的函数。例如,如果我想写一个函数,比如。。。

//returns a refrence to a string
string& returnRefrence(){

    string hello = "Hello there";
    string * helloRefrence = &hello;
    return *helloRefrence;
}
//and if i wanted to use to that function to see the value of helloRefrence would i do something like this?
string hello = returnRefrence();
cout << hello << endl;

等函数

string& returnRefrence(){}

只有在is可以访问超出其自身范围的string的情况下才有意义。例如,这可以是具有string数据成员的类的成员函数,也可以是可以访问某个全局字符串对象的函数。在函数体中创建的字符串在退出该作用域时会被销毁,因此返回对它的引用会导致悬空引用。

另一个有意义的选项是,如果函数通过引用tkaes一个字符串,并返回对该字符串的引用:

string& foo(string& s) {
  // do something with s
  return s;
}

您也可以将变量声明为static:

std::string &MyFunction()
{
    static std::string hello = "Hello there";
    return hello;
}

但是,请注意,每次调用都会返回完全相同的字符串对象作为引用。

例如,

std::string &Call1 = MyFunction();
Call1 += "123";
std::string Call2 = MyFunction(); //Call2 = "Hello there123", NOT "hello there"

Call2对象与Call1中引用的字符串相同,因此它返回了修改后的值

相关文章: