c++ – Member pointers or reference arguments? – Education Career Blog

I have the following problem.

I got a class PluginLoader which oversees loading of plugins. It divides sub-stages of work to other classes like Plugin. Plugin calls functions of PluginLoader in its processing. Let’s call that function AddData. Here, PluginLoader has to check if the data it receives is duplicate. For that, it uses a ConflictResolver class. Now, my problem is how to make an object of ConflictResolver available to PluginLoader. There are 3 ways I see out of this.

  1. Use a ConflictResolverFactory class and create an object of ConflictResolver for PluginLoader.
  2. Pass a constructed ConflictResolver* to the PluginLoader via its constructor or a member function SetConflictResolver and store it in a member variable and use it later. Both ways have drawbacks. If I pass it in the constructor, I will have to throw if the pointer is NULL. And I can’t use exceptions as it is the custom here. If I pass it via SetConflictResolver, there is no way that I can guarantee that that function will be actually called by the user. Or I will have to check whether the member ConflictResolver* is NULL everywhere I use it.
  3. Pass a ConflictResolver & to PluginLoaders Load method where all the work will be done. In turn, Plugins Load method has to accept a ConflictResolver & as well (though it has no use for it) and pass that back to AddData where PluginLoader will be able to use it.

Third method is safer compared to second. However, I have to pass around a reference even when it is not used.

If the first method cannot be used, what is the best way to do this?

Apologies for the wall :wq!

,

You could pass a ConflictResolver& to the PluginLoader constructor. You can now guarantee that the object is not null.

Leave a Comment