I have been around the C++ community for a while to hear that raw pointers "are evil" and that they should be avoided as much as possible. While one of the main reasons to use smart pointers over raw pointers is to "prevent" memory leaks. So my question is: Even when using smart pointers, is it still possible to have memory leak ? If yes how will that be possible ?
Even when using smart pointers, is it still possible to have memory leak ?
Yes, if you are not careful to avoid creating a cycle in your references.
If yes how will that be possible ?
Smart pointers based on reference counting (such as shared_ptr) will delete the pointed-to-object when the reference count associated with the object drops to zero. But if you have a cycle in your references (A->B->A, or some more elaborate cycle), then the reference counts in the cycle will never drop to zero because the smart pointers are "keeping each other alive".
Here is an example of a simple program that leaks memory despite using only using shared_ptr for its pointers. Note that when you run it, the constructors print a message but the destructors never do:
#include <stdio.h>
#include <memory>
using namespace std;
class C
{
public:
C() {printf("Constructor for C: this=%p\n", this);}
~C() {printf("Destructor for C: this=%p\n", this);}
void setSharedPointer(shared_ptr<C> p) {pC = p;}
private:
shared_ptr<C> pC;
};
int main(int argc, char ** argv)
{
shared_ptr<C> pC(new C);
shared_ptr<C> pD(new C);
pC->setSharedPointer(pD);
pD->setSharedPointer(pC);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With