I'm designing a class structure in C++ and am using abstract classes to specify interfaces between objects and make classes easily replaceable by mock objects. The problem arose when a colleague pointed out to me he could not link the program because the abstract class didn't have any implementation for the destructor. (That also sparked a discussion about pure virtual dtors vs. virtual dtors like [Why do we need a pure virtual destructor in C++? and [http://www.gotw.ca/gotw/031.htm] but should only be a side note in this question).
class Abstract {
public:
virtual void methodA() = 0;
}
class Derived : Abstract {
public:
void methodA() override;
}
The code using the classes looked like this:
std::unique_ptr<Derived> dInstance = std::unique_ptr<Derived>(new Derived());
and compiles fine. Same goes for:
std::unique_ptr<Abstract> aInstance = std::unique_ptr<Abstract>(new Derived());
When using raw pointers like so:
Derived* dInstance = new Derived();
delete dInstance;
it won't event compile. Does std::unique_ptr, and more specifically it's usage of std::default_delete do anything special when trying to delete the object? Why does this compile when I use the unique_ptr but not when I trying to do it by hand? I'm on gcc7.3 and with C++11 as standard.
Aucun commentaire:
Enregistrer un commentaire