gpt4 book ai didi

c++ - 局部变量作用域问题

转载 作者:可可西里 更新时间:2023-11-01 16:54:43 29 4
gpt4 key购买 nike

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

我认为根据 C++ 标准 3.3.2,“在 block 中声明的名称是该 block 的本地名称。它的潜在作用域从其声明点开始,到其声明区域结束。

#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);

是一个临时对象,它只在那个表达式中存在;

MyClass m(12345);

是一个对整个 block 都有效的对象。

关于c++ - 局部变量作用域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1388685/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com