Skip to content

Conversation

yoshoku
Copy link
Contributor

@yoshoku yoshoku commented May 9, 2023

This pull request solves the problem caused by BaseFilterFunctor not having a virtual destructor.

Example code:

#include <iostream>
#include "hnswlib/hnswlib.h"

class CustomFilterFunctor : public hnswlib::BaseFilterFunctor {
  public:
    CustomFilterFunctor() {
      std::cout << "constructor called" << std::endl;
    }

    bool operator()(hnswlib::labeltype id) {
      return id % 2 == 0;
    }

    ~CustomFilterFunctor() {
      std::cout << "destructor called" << std::endl;
    }
};

int main(int argc, char* argv[]) {
  hnswlib::BaseFilterFunctor* filter = new CustomFilterFunctor();
  delete filter;
  return 0;
}

Compiling with -Wall option, a warning message about the lack of a virtual destructor is output:

$ g++ -Wall -std=c++11 example.cpp
example.cpp:19:3: warning: delete called on non-final 'hnswlib::BaseFilterFunctor' that has virtual functions but non-virtual destructor [-Wdelete
-non-abstract-non-virtual-dtor]
  delete filter;
$ ./a.out
constructor called

CustomFilterFunctor's destructor was not called because the implicitly created BaseFilterFunctor's destructor was called. For example, when CustomFuncFilter is an implementation that releases the allocated memory in it's destructor, the problem occurs that the destructor is not called and the memory is not released. This issue is resolved by adding a virtual destructor to BaseFilterFunctor.

@dyashuni
Copy link
Contributor

@yoshoku Good catch, thank you!

@dyashuni dyashuni merged commit 1925428 into nmslib:develop May 13, 2023
@yoshoku yoshoku deleted the add_virtual_destructor branch May 14, 2023 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants