Any differences between f (const string &) and f (const string)?

class mystring {
 friend ostream& operator<<(ostream &out, const mystring ss) {
        out << ss.s;
        return out;
    }
private:
    string s;
public:
    mystring(const char ss[]) {
        cout << "constructing mystring : " << ss << endl;
        s = ss;
    }
};

void outputStringByRef(const mystring &ss) {
 cout << "outputString(const string& ) " << ss << endl;
}

void outputStringByVal(const mystring ss) {
 cout << "outputString(const string ) " << ss << endl;
}

int main(void) {
    outputStringByRef("string by reference");
    outputStringByVal("string by value");
    outputStringByRef(mystring("string by reference explict call mystring consructor"));
    outputStringByVal(mystring("string by value explict call mystring constructor"));
} ///:~

Given the above example, we could not change the pass-by-reference variable, and we could not change the pass-by-value variable. The result of each method is the same. Since there is no difference between the two methods, why does C ++ support both methods?

thanks.

+5
source share
7 answers

There is a difference between the two. Consider the following:

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

string g_value;

void callback() {
    g_value = "blue";
}

void ProcessStringByRef(const string &s) {
    callback();
    std::cout << s << "\n";
}

void ProcessStringByValue(const string s) {
    callback();
    std::cout << s << "\n";
}

int main() {
    g_value = "red";
    ProcessStringByValue(g_value);
    g_value = "red";
    ProcessStringByRef(g_value);
}

Output:

red
blue

, const , , ( , , "" ). , const const - . , .

, ++ , .

- , , . , - , . ProcessStringByRef , callback() . ProcessStringByValue , , .

, , . , , , , . , , . " " restrict C99.

+19

f(const string&) const: f , : . const .

f(const string) , , f . const, f.

, " ++ ?". , .

+8

f(string s) s, , , . , , . f(const string s) const , .

f(const string& s) , . , , "pass-by-value" ( ++ ). , "" , , - const . "".

+6

mutable, const

+3

outputStringByRef , , , , outputStringByRef. outputStringByVal , , , , , .

+1

() . , . const mystring &ss const . , , . , ( copy-on-write). const mystring ss , .

const mystring &ss , const_cast<mystring&>, .

+1

, , :

Thread th;
// ...
cout << th; // print out informations...

, th . , ( ?).

. th ++ , Java, - , . , " Java Object.clone, ?" - .

, . , - .

+1
source

All Articles