tags:

views:

166

answers:

3

sorry for my inattension, in short the ~CSArray() is work, but interface and implementation of the class there was in different files, so mistake is here

+4  A: 

Be sure that you declared your destructor virtual in the base class.

ereOn
`virtual`, CSObject destuctor is invoked only,
Ariel
@Ariel: Can you post the code which is using this method?
Naveen
+2  A: 

The shown code is currently too short to see the problem.

Some good advice: Never ever build your own reference-counting scheme. Use proven library-implementations like std::auto_ptr, boost::shared_ptr, or boost::shared_array and take advantage of RAII (http://en.wikipedia.org/wiki/RAII). Also, avoid "delete this" like the plague. It may seem to work in some cases, but generally the pre/postconditions are too much.

Markus Kull
Studying the conditions on `delete this;` is a good idea before attempting reference counting, but reference-counting is neither complicated nor difficult, as evidenced by the HUGE number of COM components, all of which implement `IUnknown`. Also, the classes you suggest aren't thread-safe, so "reuse the library version" could make a lot of trouble.
Ben Voigt
@Ben: And OP's code is thread-safe? Also see http://stackoverflow.com/questions/692438/is-boost-shared-ptr-xxx-thread-safe
UncleBens
Markus, I like Cocoa style in, so I make them
Ariel
+1  A: 

Assuming that _retainCount = 0

It works, provided you have declared your destructor virtual in base class.

See below code: (gcc version 3.4.3)

#include<iostream>
using namespace std;

class A
{
    public:
        A(){cout<<"A ctor"<<endl;};
        virtual ~A(){cout<<"A dtor"<<endl;};
        void testDel()
        {
            delete this;
        }
};

class B: public A
{
    public:
        B(){cout<<"B ctor"<<endl;};
        ~B(){cout<<"B dtor"<<endl;};
};

int main()
{
    B bObj;

    bObj.testDel(); 
   return 0; 
}

Result: w/o explicit delete

A ctor
B ctor
B dtor
A dtor

Result: with explicit delete

A ctor
B ctor
B dtor
A dtor
B dtor
A dtor
Kedar
I'm not quite sure what you mean by "works perfectly"; deleting an automatic variable gives undefined behaviour, and is as likely to crash as to give the double-destruction you got.
Mike Seymour
@Mike Seymour I was just to demonstrate that the destructor is called. Well I should remove word "perfectly" :) ... I didn't consider for UB here ...
Kedar