简体   繁体   中英

Why is destructor not called for private nested class in c++?

So this is my code in Car.h

#pragma once

#include<iostream>
#include<string>
using namespace std;

class Car
{

private:
    int speed;
    class GearBox;
    GearBox& gearBox;

public:
    Car();
    ~Car();
};

class Car::GearBox {
private:
    int gear;

public:
    GearBox();
    ~GearBox();
};

In Car.cpp i have

#include"Car.h"


    Car::Car(): speed(0), gearBox(GearBox())
{
    cout << "Car constructor" << endl;

}


Car::~Car()
{
    cout << "Car destructor" << endl;
}

Car::GearBox::GearBox(): gear(0)
{
    cout << "Gearbox constructor" << endl;
}

Car::GearBox::~GearBox()
{
    cout << "GearBox destructor" << endl;
}

and my main is:

#include"Car.h"


int main() {

    {
        cout << "Starting program!" << endl;

        Car car;

    }

    system("PAUSE");
    return 0;
}

Result of the program is: Starting program! GearBox constructor Car constructor Car destructor

Why is Gearbox destructor not outputted? (it makes sense to me that car has a reference to his gearbox because gearbox should exist while car does exist)

This would have to be a compiler bug, potentially related to the fact that it allows that reference initialisation in the first place (which is a Visual Studio extension, not compliant to any version of the actual, standardised, C++ language).

I believe I can reproduce this using an online VS compiler:

复制截图

C++ compilers are allowed to elide copy operations even if they contain output like this, but not constructors and destructors.

Is GearBox instantiated?

Car::Car(): speed(0), gearBox(GearBox())
{
    cout << "Car constructor" << endl;
}

Car::Car(): speed(0)
{
static GearBox inst;
gearBox = inst;
cout << "Car constructor" << endl;
}

EDIT:

class Car
{
private:
    int speed;
    class GearBox { // referable
    private:
        int gear;
    public:
        GearBox() : gear(0) {
            cout << "Gearbox constructor" << endl;
        }
        ~GearBox() {
            cout << "GearBox destructor" << endl;
        }
    };
    GearBox* gearBox;

public:
    Car();
    ~Car();
};

Car::Car(): speed(0)
{
    static GearBox inst;
    gearBox = &inst;
    cout << "Car constructor" << endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM