局部变量作用域问题 [英] Local variable scope question

查看:18
本文介绍了局部变量作用域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码打印xxY"?局部变量不应该存在于整个函数的范围内吗?我可以使用这样的行为,还是会在未来的 C++ 标准中改变?

Why is the following code prints "xxY"? Shouldn't local variables live in the scope of whole function? Can I use such behavior or this will be changed in future C++ standard?

我认为根据 C++ 标准 3.3.2在块中声明的名称对该块来说是局部的.它的潜在范围从它的声明点开始,并在其声明区域的末尾结束."

I thought that according to C++ Standard 3.3.2 "A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region."

#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":


Based on the responses I can assume that MyClass(12345); is the expression (and scope). That is make sense. So I expect that the following code will print "xYx" always:

MyClass (12345), cout << "Y" << endl;

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

And it is allowed to make such replacement:

// 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

推荐答案

您正确引用了标准.让我强调一下:

You quoted standard correctly. Let me emphasize:

块中的名称 声明是该块的本地.它的潜在作用域从它的声明点开始,到其声明区域的末尾结束.

A name declared in a block is local to that block. Its potential scope begins at its point of declaration and ends at the end of its declarative region.

实际上,您没有声明任何名称.你的线

You didn't declare any name, actually. Your line

MyClass (12345);

甚至不包含声明!它包含一个表达式,它创建一个 MyClass 的实例,计算表达式(但是,在这种特殊情况下没有什么可计算的),并将其结果转换为 void,并销毁在那里创建的对象.

does not even contain a declaration! What it contains is an expression that creates an instance of MyClass, computes the expression (however, in this particular case there's nothing to compute), and casts its result to void, and destroys the objects created there.

一个不那么令人困惑的事情听起来像

A less confusing thing would sound like

call_a_function(MyClass(12345));

你看过很多次,知道它是如何工作的,不是吗?

You saw it many times and know how it works, don't you?

这篇关于局部变量作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆