相关疑难解决方法(0)

局部变量范围问题

为什么以下代码打印"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;
}
Run Code Online (Sandbox Code Playgroud)

基于响应,我可以假设这MyClass(12345);是表达式(和范围).这是有道理的.所以我希望以下代码将始终打印"xYx":

MyClass (12345), cout << "Y" << endl;
Run Code Online (Sandbox Code Playgroud)

并且允许进行这样的替换:

// this much strings with explicit scope
{
  boost::scoped_lock lock(my_mutex); …
Run Code Online (Sandbox Code Playgroud)

c++ scope raii

8
推荐指数
3
解决办法
1419
查看次数

标签 统计

c++ ×1

raii ×1

scope ×1