Opened 6 years ago

Last modified 6 weeks ago

#9947 accepted enhancement

False negative: Missing virtual destructor (pointer alias)

Reported by: Daniel Marjamäki Owned by: Tommy Bergman
Priority: Normal Milestone:
Component: Improve check Version:
Keywords: virtualDestructor Cc:

Description

We have (had) some check for missing virtual destructors. Not sure why it does not warn below:

#include <memory>
#include <string>
#include <iostream>

class Fred {
public:
    Fred() { std::cout << "Fred\n"; }
    ~Fred() { std::cout << "~Fred\n"; }
};

class Base {
public:
    Base() { }
};

class Derived : public Base {
public:
    Derived() : Base(), x(std::make_shared<Fred>()) {}
private:
    std::shared_ptr<Fred> x;
};

int main() {
    Derived *derived = new Derived;
    Base *base = derived;
    delete base;
    return 0;
}

The message "~Fred" is not written so there seems to be a memory leak.

Change History (5)

comment:1 by chrchr, 4 years ago

Keywords: virtualDestructor added

comment:2 by chrchr, 4 years ago

We warn for

	Base *base = new Derived;
	delete base;

but not for

	Derived *derived = new Derived;
	Base *base = derived;
	delete base;

We should probably just warn based on the class definition instead of trying to detect all possible use cases:

	std::vector<std::unique_ptr<Base>> v(1);
	v[0].reset(new Derived);
Last edited 4 years ago by chrchr (previous) (diff)

comment:3 by Daniel Marjamäki, 21 months ago

We should probably just warn based on the class definition instead of trying to detect all possible use cases:

The current checker writes a error message so it needs to be explicit. But yes I think we could add a warning or style checker that just enforce that base classes overall provide virtual destructors. I suggest that separate IDs would be used.

Imho, it's a really good idea to always provide virtual destructors in base classes. Maybe except if it can be seen that the derived destructor does nothing.

Last edited 21 months ago by Daniel Marjamäki (previous) (diff)

comment:4 by chrchr, 5 months ago

Summary: False negative: Missing virtual destructorFalse negative: Missing virtual destructor (pointer alias)

comment:5 by Tommy Bergman, 6 weeks ago

Owner: changed from noone to Tommy Bergman
Status: newaccepted
Note: See TracTickets for help on using tickets.