Destruction order for an array of objects

class MyClass
{
};

void foo
{
    MyClass arr[10]; 
}

I want to know the order in which array objects are destroyed when the function returns.

I read this more efficient C ++ about it, and it says that the destructor is called in reverse order to order of the constructor as follows:

for(int i = 9 ; i >= 0 ;i--)
{
    arr[i].MyClass::~MyClass();
}

Can someone tell me the reason for this?

+5
source share
5 answers

++. , , , RAII. ( / ) .

+2

, More Effective ++, , , :

class Foo {
  private:
     Bar bar_1;
     Bar bar_2;

  public:
     Foo() : bar_1(), bar_2() {}
};

bar_1, bar_2. Foo , bar_2 , bar_1. , .

, , , , .

, , , . , (, POD , , , POD). , .

, , ( , IMHO). , , , .

+2

, . , , . . , ( , LIFO)

+1

, , , , . , , .

0

, , , , , .

. , . , . , , .

0 9, 9 0 . ( g++-4.2 Mac OS X.)

#include <iostream>

class MyClass
{
public:

    MyClass()
    {
        mCounter = kInstanceCount++;
        std::cout << "+++ MyClass() " << mCounter << std::endl;
    }

    ~MyClass()
    {
        std::cout << "--- MyClass() " << mCounter << std::endl;
    }

private:
    unsigned            mCounter;
    static unsigned     kInstanceCount;
};

unsigned MyClass::kInstanceCount = 0;

int main()
{
    MyClass arr[10];
    return 0;
}

++, 100%, ( ), .

, . , , std::vector, , , , .

0

All Articles