次のコードで「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);
が式(およびスコープ)であると推測できます。それは理にかなっています。したがって、次のコードは常に「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