按值传递字符串:
#include
#include
void modifyString(std::string str) {
str = "Modified";
std::cout << "Inside modifyString function: " << str << std::endl;
}
int main() {
std::string str = "Original";
modifyString(str);
std::cout << "After modifyString function: " << str << std::endl;
return 0;
}
按引用传递字符串:
#include
#include
void modifyString(std::string& str) {
str = "Modified";
std::cout << "Inside modifyString function: " << str << std::endl;
}
int main() {
std::string str = "Original";
modifyString(str);
std::cout << "After modifyString function: " << str << std::endl;
return 0;
}
按 rvalue 传递字符串(使用 std::move):
#include
#include
void modifyString(std::string&& str) {
str = "Modified";
std::cout << "Inside modifyString function: " << str << std::endl;
}
int main() {
std::string str = "Original";
modifyString(std::move(str));
std::cout << "After modifyString function: " << str << std::endl;
return 0;
}