'Reassigning pointer argument inside function in C++ [duplicate]
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
In the following code, s==nullptr gets printed. Why did assignment to s inside the function assign_string not reflected in the main function?
#include<iostream>
#include<string>
void assign_string(std::string* s)
{
s = new std::string("Reassigned");
}
int main()
{
std::string* s = nullptr;
assign_string(s);
if (s == nullptr)
{
std::cout << "s==nullptr" << std::endl;
}
else
{
std::cout << "s!=nullptr" << std::endl;
}
return 0;
}
PS: I'm new to C++ and I might be using terms like "assign" loosely.
EDIT. Is passing pointer argument, pass by value in C++? has many useful answers.
Solution 1:[1]
If I pass a pointer to a function as an argument and assign to the pointer inside the function, shouldn't that be reflected in the calling scope?
No. When you pass an object by value, the parameter and the argument are separate objects. Modifying one object has no effect on the other object. This applies to all objects, including pointers.
In order to modify an object outside of the function, you need to use indirection. There are two forms of indirection: Pointers and references. So, in order to modify a pointer that is outside of the function, you need to pass a reference or a pointer to the pointer. Example:
void assign_string(std::string*& s);
PS: I'm new to C++
I recommend learning early that owning bare pointers are a bad idea and there is hardly ever a need to use them nor to use allocating new expressions. It's quite rare to need to dynamically allocate a std::string object or any other container.
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 |
