【发布时间】:2010-11-26 04:45:01
【问题描述】:
为什么下面的代码会打印“xxY”?局部变量不应该存在于整个函数的范围内吗?我可以使用这种行为吗?或者这将在未来的 C++ 标准中改变?
我认为根据 C++ 标准 3.3.2 “在块中声明的名称是该块的本地名称。它的潜在范围从其声明点开始,并在其声明区域的末尾结束。 em>"
#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
【问题讨论】:
-
您的问题包含答案:已声明的名称...。没有名字!
-
在此示例中:MyClass(12345) 是函数样式转换,而不是声明。
-
仍然没有实例名称