CPP, Variables don't go out of scope

时间:2016-02-03 04:19:51

标签: c++ memory scope destructor

in all my other experiments i have done, my variables go out of scope as intended, but when i put variables in the main method, they don't go out of scope or that's what it seems like because the destructor never gets called:

#include <string>
#include <iostream>

using namespace std;

#define PRINT(s) cout << s
#define PRINTLN(s) PRINT(s) << endl

class Animal
{
public:
    string name;
    int legs;

    Animal(string name, int legs) {
        this->name = name;
        this->legs = legs;
    }

    ~Animal(){
        PRINTLN("deleting");
    }
    static Animal createAnimal() {
        PRINTLN("creating");
        return Animal("animal", 4);
    }
};

int main() {
    PRINTLN("start");
    Animal a = Animal::createAnimal();//or Animal a("hello", 5);
    PRINTLN("end running method");

    PRINTLN("end");
    system("pause");
    return 0;
    //should print out "deleting" here 
    //because of a going out of scope
}

1 个答案:

答案 0 :(得分:0)

At the point in your code where you have the comment

//should print out "deleting" here 
//because of a going out of scope

"a" isn't out of scope. It will go out of scope as the application terminates. Other similar questions (Are destructors run when calling exit()?) discuss what you can expect when the application terminates.