locked
About destructor RRS feed

  • Question

  • In the DirectX metro sample one can find a class named DirectXBase with roughly this header

    ref class DirectXBase abstract
    {
    public:
        DirectXBase();
    
        virtual void Render() = 0;
        virtual void Present();
        /// ...............
    
    protected:
    
        // Declare Direct2D Objects
        Microsoft::WRL::ComPtr<ID2D1Factory1>           m_d2dFactory;
        Microsoft::WRL::ComPtr<ID2D1Device>             m_d2dDevice;
        Microsoft::WRL::ComPtr<ID2D1DeviceContext>      m_d2dContext;
        Microsoft::WRL::ComPtr<ID2D1Bitmap1>            m_d2dTargetBitmap;
        //.............
    };
    


    What I find strange is that there is no destructor!

    What about all those ComPtr? are they automatically set to null because it's a ref class?

    is it a bug?

    Tuesday, January 24, 2012 3:18 PM

All replies

  • Whether or not you define a destructor, the compiler will ensure that any class members that you hold will have their destructors called when your class is destroyed.

    You will find that Microsoft::WRL::ComPtr does have a destructor to release their COM handles.

    Wednesday, January 25, 2012 8:59 PM
  • Thanks for that!

    In fact I'm a little bit of a C++ newbie as well. Anyway, to make things clear to me I tried the following test, created a header

    Lang.h

    #pragma once
    
    ref class Lang
    {
    public:
    	Lang(int n);
    	~Lang();
    
    	void Poo();
    
    private:
    	Lang^ sub;
    	int n0;
    };
    
    Lang::Lang(int n)
    : n0(n), sub(nullptr)
    {
    	if(n>0)
    		sub = ref new Lang(n - 1);
    	Platform::Console::WriteLine("Lang(" + n0.ToString() + ")");
    }
    
    Lang::~Lang()
    {
    	Platform::Console::WriteLine("~Lang(" + n0.ToString() + ")");
    }
    
    void Lang::Poo()
    {
    	Platform::Console::WriteLine("Lang::Poo(" + n0.ToString() + ")");
    	if (sub != nullptr)
    		sub->Poo();
    }<br/>
    

    And then I tested it by adding this in InitializeComponent() of my main window:

    	{
    		auto a = ref new Lang(3);
    		a->Poo();
    	}
    	{
    		Lang a(2);
    		a.Poo();
    	}
    
    

    And used break points to follow control flow (as neither std::cout nor Platform::Console::WriteLine seemed to work)

    I'm a little confused now.

    I was glad to see that the destructors were automatically called.

    However a.Poo() (in the second block) caused a violation exception!!!
    Apparently a.sub->sub->sub->n0 is the source of the memory access problem!

    What is wrong here?? 

    Thursday, January 26, 2012 3:02 AM