我认为根据C++标准3.3.2,“在块中声明的名称只在该块中本地。其潜在范围始于其声明点,结束于其声明区域的末尾。”
#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