Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Potential delete from stack

Status
Not open for further replies.

RichardF

Programmer
Oct 9, 2000
239
GB
Hi,

The title makes it sound bad. I'll explain by example.
Sorry about the volume of code, but its simple.

template <class A>
class Pointer {
public:
Pointer():ptr(NULL) {};
Pointer() { if (ptr) delete ptr; };

void Add(T *pValue) {
ptr = pValue;
}

void Add(T &Value) {
Add(&Value);
}

private:
T* ptr;
};


class RF {
public:
RF():Age(0) {};
void SetAge(int Value) { Age = Value };
private:
int Age;
};


int main() {
RF Sue;

Sue.SetAge(21);

Pointer<RF> *P = new Pointer<RF>;

P->Add(Sue);

// .... do something

delete P;

return 0;
}

Finally, the question is. When I call delete P, which calls the Pointer destructor to delete ptr - do i have to distingush between variables that come from the stack or the heap ? will Sue be deleted twice ?

Thanks in advance.

Rich.

 
void Add(T &Value) {
Add(&Value);
}

BAD... VERY BAD

You should get a copy of Myers &quot;More Effective C++&quot; or whatever the latest version is.

If you add a destructor to your template that deletes &quot;ptr&quot; it will blow chunks.

I don't know what your trying to do exactly, what you posted is ok since your template class has no destructor defined the deletes &quot;ptr&quot;.

Perhaps you could explain your goal.

-pete
 
Hi Pete,

Sorry this line:

Pointer() { if (ptr) delete ptr; };

should have read :

~Pointer() { if (ptr) delete ptr; };

All that aside, that was just an example that illustrates what i was trying to do. I didnt want to post reams of the real thing.

This explains why it blows up when the program completes. I understand now.

Thanks.
 
Rich, sounds like you have a handle now, but yeah you can't delete stack based memory only heap based allocations.

-pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top