'Reusing String in C++ in function [closed]
As someone whose main language has been Python so far, I have a problem with string reuse.
Here's an example code (simplified):
void function(std::string &basicString)
{
std::cout << "Function print: " << &basicString << "\n";
}
int main()
{
std::vector<std::string> x_files;
/*
Does sth, x_files contains some strings
*/
for (std::vector<std::string>::size_type i = 0; i != x_files.size(); i++) {
std::string temp = x_files[i];
std::cout << temp << "\n";
function(temp);
}
return 0;
}
The thing is, as a result I'd like to have this:
my_string
Function print: my_string
Instead, I get this:
my_string
Function print: 0x7cd2346eaf1827cd
0x7cd2346eaf1827cd - not exactly what I get every time, but an example.
Solution 1:[1]
std::cout << "Function print: " << &basicString << "\n";
Here you use unary & operator, which is an address-of operator, in other words it gives you a pointer. And since this is not a char pointer, std::cout prints the pointer value, in other words a memory address, as hex.
Solution is simple, remove &:
std::cout << "Function print: " << basicString << "\n";
Perhaps you're getting confused about pointers, because if instead of reference you used a pointer, you'd do this:
void function(std::string *basicString)
{
std::cout << "Function print: " << *basicString << "\n";
}
Pointers and references are quite similar, but they are not the same, including this difference in how they are declared and used.
Finally, you probably want to pass a const reference:
void function(const std::string &basicString)
You should always use const with a reference parameter, unless you intend to modify the original.
Solution 2:[2]
C++(like many other) is a context based language. For example, in you given snippet, when you wrote:
void function(std::string &basicString) //here basicString is a lvalue reference to std::string
{
}
In the above snippet, you're defining a function named function that take one parameter whose type is an lvalue reference to a std::string. That is, the & symbol represents an lvalue reference in this context.
On the other hand, when you wrote:
std::cout << "Function print: " << &basicString << "\n";
Here the & symbol means that you're taking the address of the variable to which basicString refers.
Solution
To solve this you just have to remove the & symbol as shown below:
void function(std::string &basicString) //NO NEED TO REMOVE & FROM HERE
{
std::cout << "Function print: " << basicString << "\n"; //REMOVED & FROM HERE
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Anoop Rana |
