@@ -169,6 +169,7 @@ class ClassLoader
169169 template <class Base >
170170 Base * createUnmanagedInstance (const std::string & derived_class_name)
171171 {
172+ class_loader_ref_count--;
172173 return createRawInstance<Base>(derived_class_name, false );
173174 }
174175
@@ -252,6 +253,15 @@ class ClassLoader
252253 CLASS_LOADER_PUBLIC
253254 int unloadLibrary ();
254255
256+ void removeWhenPosible ()
257+ {
258+ this ->remove_when_possible = true ;
259+ if (class_loader_ref_count == 0 ) {
260+ unloadLibraryInternal (false );
261+ delete this ;
262+ }
263+ }
264+
255265private:
256266 /* *
257267 * @brief Callback method when a plugin created by this class loader is destroyed
@@ -271,9 +281,15 @@ class ClassLoader
271281 delete (obj);
272282 assert (plugin_ref_count_ > 0 );
273283 --plugin_ref_count_;
274- if (plugin_ref_count_ == 0 && isOnDemandLoadUnloadEnabled ()) {
284+ --class_loader_ref_count;
285+ if (plugin_ref_count_ <= 0 && isOnDemandLoadUnloadEnabled ()) {
275286 if (!ClassLoader::hasUnmanagedInstanceBeenCreated ()) {
276- unloadLibraryInternal (false );
287+ if (class_loader_ref_count == 0 ) {
288+ unloadLibraryInternal (false );
289+ }
290+ if (remove_when_possible) {
291+ delete this ;
292+ }
277293 } else {
278294 CONSOLE_BRIDGE_logWarn (
279295 " class_loader::ClassLoader: "
@@ -331,7 +347,7 @@ class ClassLoader
331347 std::lock_guard<std::recursive_mutex> lock (plugin_ref_count_mutex_);
332348 ++plugin_ref_count_;
333349 }
334-
350+ class_loader_ref_count++;
335351 return obj;
336352 }
337353
@@ -365,6 +381,8 @@ class ClassLoader
365381 int plugin_ref_count_;
366382 std::recursive_mutex plugin_ref_count_mutex_;
367383 static bool has_unmananged_instance_been_created_;
384+ unsigned int class_loader_ref_count;
385+ bool remove_when_possible;
368386};
369387
370388} // namespace class_loader
0 commit comments