简体   繁体   中英

Function that returns an string refrence c++

im new to pointers and refrences in c++ so i was wondering if someone could show me an example of how to write a function that returns a string refrence and maybe the function being used. For example if i wanted to write a function like...

//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;

A function such as

string& returnRefrence(){}

would only make sense in a context where is has access to a string that lives beyond it's own scope. This could be, for example, a member function of a class that has a string data member, or a function that has access to some global string object. A string created in the body of the function is destroyed on exiting that scope, so returning a reference to it results in a dangling reference.

Another option where is could make sense is if the function tkaes a string by reference, and returns a reference to that very string:

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

You could also declare the variable as static:

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

However, note that the exact same string object will be return as reference on each call.

For instance,

std::string &Call1 = MyFunction();
Call1 += "123";

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

The Call2 object is the same string referenced in Call1, so it returned its modified value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM