0

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.

ethelion
  • 105
  • 6
  • 1
    The pointers are not special in this regard, a (non-reference) parameter is always a copy of whatever was passed to it. Writing to a *dereferenced* pointer parameter, hovewer, is visible to the caller. – HolyBlackCat Apr 16 '22 at 19:56
  • You almost never need `new` in modern C++. `assign_string` is pointless since you can just assign a new value to a `std::string` object instead of reassigning a pointer to a new `std::string` object. This might just be an example, but you probably don't need any pointers at all if you are using `std::string`. – user17732522 Apr 16 '22 at 20:04
  • In my real code, I had a pointer to a different class which I was passing as an argument to a function. A need to pass that pointer to the function might also be questionable though. For now, I am just trying to get familiar with the concepts. – ethelion Apr 16 '22 at 20:10

1 Answers1

0

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326