CPP,变量不要超出范围
CPP, Variables don't go out of scope
在我所做的所有其他实验中,我的变量按预期超出了范围,但是当我将变量放在 main 方法中时,它们没有超出范围或者看起来就是这样,因为析构函数永远不会被调用:
#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
}
在您的代码中您有注释的地方
//should print out "deleting" here
//because of a going out of scope
"a" 没有超出范围。当应用程序终止时,它将超出范围。其他类似问题 (Are destructors run when calling exit()?) 讨论了应用程序终止时您可以期待什么。
在我所做的所有其他实验中,我的变量按预期超出了范围,但是当我将变量放在 main 方法中时,它们没有超出范围或者看起来就是这样,因为析构函数永远不会被调用:
#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
}
在您的代码中您有注释的地方
//should print out "deleting" here
//because of a going out of scope
"a" 没有超出范围。当应用程序终止时,它将超出范围。其他类似问题 (Are destructors run when calling exit()?) 讨论了应用程序终止时您可以期待什么。