为什么以下编码印刷“xxY”? 是否有地方变量属于整个功能的范围? Can 我使用这种行为,或在今后的C++标准中加以改变?
我认为,根据C++标准3.2“A名称在一栏被宣布为当地人。 其潜在范围始于声明点,并在声明区域结束时结束。
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass( int ) { cout << "x" << endl; };
~MyClass() { cout << "x" << endl; };
};
int main(int argc,char* argv[])
{
MyClass (12345);
// changing it to the following will change the behavior
//MyClass m(12345);
cout << "Y" << endl;
return 0;
}
根据答复,我可以假定,<代码>MyClass(12345);是表述(和范围)。 这是有意义的。 因此,我预计以下法典将永远印刷“xYx”:
MyClass (12345), cout << "Y" << endl;
并且允许替换:
// this much strings with explicit scope
{
boost::scoped_lock lock(my_mutex);
int x = some_func(); // should be protected in multi-threaded program
}
// mutex released here
//
// I can replace with the following one string:
int x = boost::scoped_lock (my_mutex), some_func(); // still multi-thread safe
// mutex released here