Created
January 30, 2018 17:27
-
-
Save vietjtnguyen/35b431fd461158f4264159e948c7d2f9 to your computer and use it in GitHub Desktop.
Non-polymorphic destructor leak
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <memory> | |
class foo { | |
public: | |
foo(int a) | |
: a(a) { | |
std::cout << "foo(" << this->a << ")\n"; | |
} | |
~foo() { | |
std::cout << "~foo(" << this->a << ")\n"; | |
} | |
int a; | |
}; | |
class bar : public foo { | |
public: | |
bar(int a) | |
: foo(a), data(new char[4 * 1024 * 1024]) { | |
std::cout << "bar(" << this->a << ")\n"; | |
} | |
~bar() { | |
std::cout << "~bar(" << this->a << ")\n"; | |
delete[] this->data; | |
} | |
private: | |
char* data; | |
}; | |
int main() { | |
foo a(0); | |
bar b(1); | |
std::unique_ptr<foo> c(new foo(2)); | |
std::unique_ptr<foo> d(new bar(3)); // does not call ~bar() | |
std::unique_ptr<bar> e(new bar(4)); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
check: main | |
valgrind --tool=memcheck --leak-check=yes ./main | |
main: main.cpp | |
g++ main.cpp -o main -std=c++11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment