Home > Enterprise >  How do I assign an object to passed nullptr?
How do I assign an object to passed nullptr?

Time:11-08

Consider the following code:

struct MyObject {
  std::string name;
};

void getOrCreateMyObject(std::shared_ptr<MyObject> myObj) {
  if (myObj == nullptr) {
    myObj = std::make_shared<MyObject>();
    myObj->name = "Created Automatically";
  }
  std::cout << myObj->name << std::endl;
}

int main() {
  std::shared_ptr<MyObject> moPtr = nullptr;
  getOrCreateMyObject(moPtr);
  if (moPtr != nullptr) {
    std::cout << moPtr->name << std::endl;
  }
}

As you can see, I'm passing a nullptr to the function, where it checks for the nullptr and creates a shared_ptr and successfully uses the newly created object. However, returning back to main, the moPtr is still a nullptr.

So how do I make it so I can access that newly object outside the scope of that function?

Thank you in advance!

Edit: Thank you everybody. Changing the code to

void getOrCreateMyObject(std::shared_ptr<MyObject>& myObj)

did, of course, work. Somehow I wrongly assumed that passing the pointer automatically resolves to the outer pointer when leaving the function.

CodePudding user response:

Referring to this source:

There are two parameter-passing modes in C : by value,and by reference.

  • When a parameter is passed by value, the changes made to the parameter within the function do not affect the value of the actual argument used in the function call.

  • When a parameter is passed by reference, changes made to the parameter do affect the actual arguments in the client space. In addition, there is a special mode of passing array parameters.

So you are passing your parameter by value, which means any changes inside the callee function scope will affect only the copied instance of passed parameter.

  • Related