Re:Data structures and Algorithms in C/C++11
by bhangi on Wednesday December 03, 2014 @08:40PM
(#8697458)
Sorry if this is an ignorant question, but can you elaborate on this? It's not clear to me why this would lead to memory leaks.
Re:Data structures and Algorithms in C/C++11
by quizotic on Wednesday December 03, 2014 @08:48PM
(#8697482)
for example: http://stackoverflow.com/questions/461203/when-to-use-virtua...
class B : public A { ... } void foo() { A* someA = new B(...); ... delete someA; }
if A destructor is not virtual, then B's resources leak.
Re:Data structures and Algorithms in C/C++11
by gtremper on Wednesday December 03, 2014 @08:48PM
(#8697481)
This covers the standard reason
http://stackoverflow.com/questions/461203/when-to-use-virtua...
Re:Data structures and Algorithms in C/C++11
by eclipsor on Wednesday December 03, 2014 @08:49PM
(#8697484)
If the destructor isn't implemented in derived classes, they will use the parent's destructor. Not a guaranteed memory leak..... but something you need to be aware of.
Re:Data structures and Algorithms in C/C++11
by nostrademons on Wednesday December 03, 2014 @10:18PM
(#8697689)
It's worse than that - if you ever have a a variable with the static type of the base class but the dynamic type of a derived class, memory will leak, even if you've implemented the destructor in derived classes. For example, this code:
class Base {
public:
Base() {}
~Base() {}
};
class Derived : public Base {
private:
Foo* _foo;
public:
Derived() : _foo(new Foo) {}
~Derived() { delete _foo; }
};
int main() {
std::unique_ptr<Base>(new Derived);
}
The problem here is that if the destructor is not marked virtual, then when unique_ptr<Base> goes to invoke the destructor, it calls ~Base instead of ~Derived. That has no knowledge of Derived's member variables, so any memory that Derived allocated leaks. (Technically, it's undefined behavior and can do whatever it wants, but most implementations in practice will call ~Base.)
Re:Data structures and Algorithms in C/C++11
by cbd1984 on Wednesday December 03, 2014 @08:41PM
(#8697463)
So this means the code is in C++ and not in C? The title should be more explicit on that. It's like advertising your code is in C++/C#.
Re:Data structures and Algorithms in C/C++11
by deathanatos on Wednesday December 03, 2014 @08:47PM
(#8697480)
> So this means the code is in C++ and not in C? The title should be more explicit on that. It's like advertising your code is in C++/C#.
It appears to be mixed. The files ending in .c contain C, the files ending in .cpp contain C++. See the Makefile, which will compile each with the relevant compiler.
Also, did you reply to the right parent?
:(