How do I transfer responsibility from a pointer?

Asked

Viewed 47 times

2

During the implementation of the Pattern Command design, I came across the following dilemma:

"As I signal to customers of a particular class, the pointer passed as parameter will be destroyed?".

To illustrate this situation, below follows the Remotecontrol class and its use by the customers in the class.

Let’s say the Remotecontrol class has a pointer vector for commands. This class is responsible for unsetting the pointers saved on the vector during reset and destruction of the Remotecontrol object.

class RemoteControl {
private:
  vector<Command*> commands{7};
public:
  RemoteControl() {
    for(auto& cmd : commands) cmd = new NoCommand();
  }
  ~RemoteControl() {
    for(auto& ptr : commands) {
      if(ptr != nullptr) delete ptr;
    }
  }
  void set_command(int slot, Command* cmd) {
    if(commands[slot] != nullptr) delete commands[slot];
    commands[slot] = cmd;
  }
};

In this way, it is the responsibility of Remotecontrol customers to allocate Command objects, however they should not do the offset, since once a command is passed to the Remotecontrol class, the "take possession" class of the pointer.

I suspect the signature of the method set_command should change, to receive xvalues. But I never used and I never saw it with "raw pointers".

Maybe a signature of the kind

void set_command(int slot, Command* && cmd)

For customers to use the Remotecontrol class as follows:

int main()
{
  Command* cmd = new Command();
  RemoteControl* remote = new RemoteControl();

  remote->set_command( 0, std::move(cmd) );
  remote->set_command( 1, new Command() );
    
  delete remote;
  return 0;
}
  • 1

    I think this story of me creating and someone else destroying is conducive to error and a little complicated. If I create command outside the class then I should destroy it. I think passing pointer control to another class only complicates the example you have. I can imagine more complicated scenarios like doing a two-task following the command. In this case who destroys the first command? Anyway if you really want to do you can at least pass a function on set serve as callback to run whenever you will start destroying the pointer.

  • Okay. Let me get this straight. The right thing to do would be to choose one of these two objects to be responsible for creating and destroying?

  • 1

    More than that. The principle that C programmers usually follow is who builds also destroys. When you follow this philosophy, it’s easy to control and not forget things with memory leaks. When that doesn’t happen typically it becomes difficult to control. Doesn’t mean I can’t do it differently, but as you can see, it’s more complicated, and it’s not the standard.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.