Help with smart pointers


#1

Perhaps I am using smart pointers incorrectly, but I am getting in a situation where a smart pointer is returning a pointer to an object with a ref count of 0. Meaning, it’s already been deleted, and then it gets deleted a second time.

Here is a code snippet that illustrates the problem.

[code]// ptrcrash.cpp : Defines the entry point for the console application.
//

#include “stdafx.h”

class MainObject;
class InnerObject : public ReferenceCountedObject
{
public:
InnerObject(MainObject* mo_) : mo(mo_)
{
data = new char[10];
}

virtual ~InnerObject();

private:
MainObject* mo;
char* data;
};

typedef ReferenceCountedObjectPtr InnerObjectPtr;

class MainObject
{
public:
MainObject()
{
innerObject = new InnerObject(this);
}

virtual ~MainObject()
{
}

InnerObjectPtr getInnerObject() { return innerObject; }

private:
InnerObjectPtr innerObject;
};

InnerObject::~InnerObject()
{
printf("~InnerObject\n");
delete[] data;

InnerObjectPtr po = mo->getInnerObject();

}

int _tmain(int argc, _TCHAR* argv[])
{
MainObject* mo = new MainObject();
delete mo;
return 0;
}
[/code]

Also, tone.c shouldn’t be a part of juce, otherwise juce gets two functions named main.


#2

InnerObjectPtr is member value of MainObject. When MainObject gets deleted, after its destructor has been executed, InnerObjectPtr gets deleted. And in its destructor you call MainObject (mo->getInnerObject()) ?? MainObject is already dead by then… This is simply an error in design.

/R


#3