aishuishou
aishuishou

Reputation: 83

C++ passing string references into functions

I have two questions about C++ strings:

  1. The expression string func(string & s) works in a similar fashion to string & func(string & s), but how do you determine if the return value is referential or non-referential?
  2. Why can't I use func((string)str) instead?


The code is as follows, including comments showing my intent with questions 1 and 2:

#include <iostream>
#include <string>
using namespace std;

//Q1:string func(string & s){
string & func(string & s){
    s[2]='S';
    return s;
}

int main(){
    char str[]={'H','H','H','H'};
    string name="HHHHH";
    //Q2:string tmp=(string)str;
    //string rest=func(tmp);
    string rest=func((string)str);
    cout<<"rest"<<rest;
}

Upvotes: 0

Views: 196

Answers (1)

Brian Bi
Brian Bi

Reputation: 119069

Q1: Returning string& returns a reference to the original string. Returning string returns a copy of the original string. Also, returning string& makes the function call expression an lvalue, whereas returning string makes it an rvalue.

Q2: (string)str creates a temporary std::string initialized from str. Therefore it's an rvalue. But func expects its argument to be an lvalue, since the parameter is a non-const lvalue reference.

Upvotes: 3

Related Questions