可能重复:
while和for循环的范围是什么?
for (int32 segNo = 0; segNo < 10; ++segNo)
{
my_Object cm;
}
Run Code Online (Sandbox Code Playgroud)
是否会在每次通过循环时调用对象cm的构造函数和析构函数?
如果是这样,是否会在循环变量递增之前或之后调用析构函数?
#include <iostream>
struct Int {
int x;
Int(int value):x(value){}
bool operator<(int y)const{return x<y;}
void increment() { std::cout << "incremented to " << ++x << "\n";}
};
struct Log {
Log() { std::cout << "Log created\n";}
~Log() { std::cout << "Log destroyed\n";}
};
int main()
{
for(Int i=0; i<3; i.increment())
{
Log test;
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
Log created
Log destroyed
incremented to 1
Log created
Log destroyed
incremented to 2
Log created
Log destroyed
incremented to 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1192 次 |
| 最近记录: |