为什么下面的代码打印“xxY”?本地变量是否应该存在于整个函数的范围之内?我可以使用这种行为吗?或者这将在未来的C++标准中改变?局部变量范围问题
我认为根据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);
是表达式(和范围)。这是有道理的。因此,我希望下面的代码将打印“XY-X”总是:
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
你的问题包含答案:*名称声明... *。没有名字! – quamrana 2009-09-07 10:52:09
在这个例子中:MyClass(12345)是一个函数式样转换,而不是一个声明。 – 2009-09-07 10:54:21
仍然没有实例的名称 – artificialidiot 2009-09-07 11:04:29