Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct implementation of a set function for pointer variable

Tags:

c++

What is good practice to implement a set function for a class variable which is stored in a pointer (due to the need of polymorphism).

Do I pass a pointer to the set function or the object by reference? Also what is the textbook way of making sure no memory leaks exist? (Unfortunately, I can't use smart pointers.)

The way I see it I have two options:

class A {
  B* b;
  setB(B& newB) {
     delete b;
     b = &newB;
  }

  //vs:

  setB(B* newB) {
     delete b;
     b = newB;
  }
};
like image 736
user695652 Avatar asked Dec 08 '25 07:12

user695652


1 Answers

Since C++11, I believe the correct way is to use an std::unique_ptr<B>:

#include <memory>

class A {
  std::unique_ptr<B> b;
  void setB(std::unique_ptr<B>&& newB) {
     b = std::move(newB);
  }
};

and to call it, do:

std::unique_ptr<B> b(new B(/* ... */));
obj_A.setB(std::move(b));

A parameter of the type std::unique_ptr<B>&& will ensure to the user of your function that you are taking the ownership of the pointer to yourself.

EDIT:

As univise pointed, OP doesn't want to use smart pointers. I can't infer from the question why is it so, but if it is about resource usage, know that using a std::unique_ptr like this has zero overhead, either in compiled code size or in pointer object size.

like image 122
lvella Avatar answered Dec 10 '25 21:12

lvella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!