3

I have a simple piece of code to load a shared library

  std::shared_ptr<void> hnld;
  hnld.reset( dlopen("libFoo.so", RTLD_NOW),dlclose);
  if(!hnld){
    std::cout << "Failed to load. "<< std::endl;
  }

When the library is loaded everything works right, but if it fails the message is displayed, however the code crashes when calling the destructor dlclose, which is expected as the object is invalid. As !hnld is false, shouldn't know the smart pointer that the destructor shouldn't be called ?

Note I know how to solve this by using another destructor who check if the object is nullptr before calling dlclose. My question is: why does the shared pointer behave like this?

raphchar
  • 33
  • 3
  • 2
    https://en.cppreference.com/w/cpp/memory/shared_ptr/~shared_ptr This documents the behavior but does not answer why. – Daniel Aug 25 '20 at 13:49
  • 5
    The deleter for a shared_ptr has to be able to handle nullptr. Since `dlclose` doesn't handle nullptr, you'll need a helper deleter that does the nullptr check for you. – Eljay Aug 25 '20 at 13:50
  • 1
    ...and a simple lambda could do the job: [demo on coliru](http://coliru.stacked-crooked.com/a/5a498d69e7cbe8a9) – Scheff's Cat Aug 25 '20 at 14:06

0 Answers0