爲什麼下面的代碼打印「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