1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <string>
#include <iostream>
//Function takes a reference and change values in variables.
void change(std::string&, std::string&, std::string&);
//Function takes a value.
void change(std::string);
int main()
{
std::string str1, str2, str3;
str1 = "String one for change.";
str2 = "String two for change.";
str3 = "String three for change.";
//Prints addresses of data.
std::cout << &str1 << std::endl;
std::cout << &str2 << std::endl;
std::cout << &str3 << std::endl;
std::cout << std::endl;
change(str1, str2, str3);
std::cout << str1 << std::endl;
std::cout << str2 << std::endl;
std::cout << str3 << std::endl;
std::cout << std::endl;
change(str1);
change(str2);
change(str3);
return 0;
}
//This function takes addresses of data, but not data. So it works on values given variables stors.
//It do not make copy of data.
void change(std::string& inStr1, std::string& inStr2, std::string& inStr3)
{
//Prints addresses of data. It is same as above addresses.
std::cout << &inStr1 << std::endl;
std::cout << &inStr2 << std::endl;
std::cout << &inStr3 << std::endl;
std::cout << std::endl;
//Change values of variables.
std::string str = "changed";
inStr1.replace(7, 3, str);
inStr2.replace(7, 3, str);
inStr3.replace(7, 5, str);
}
//This functin takes data. So it works on copy of data stort in given variable.
void change(std::string inStr)
{
//Prints addresses of data. It is different from above addresses.
std::cout << &inStr << std::endl;
}
//First function saves time as it do not need to copy data.
//Second function makes a copy of data. And takes more memory, as here are two copys of data in memory.
|