在 C++ 中的 if 条件中创建的对象的范围
Scope of an object created in an if-condition in C++
在下面的示例中
void fun() {
if(int i=SOME_VALUE) {
// ...
} else {
// ...
}
}
i的范围是什么?我们可以在 if 块中使用它吗?我们可以在 else-block 中使用它吗?
编辑:
作为后续,在此修改后的示例中
void fun() {
if(int i=SOME_VALUE) {
// ...
} else if(int j=SOME_OTHER_VALUE){
// ...
} else {
// ...
}
}
我们可以在 else 子句中同时访问 i 和 j 吗?
是的,是的。
其典型用途是动态强制转换:
if (auto p = dynamic_cast<Derived*>(base_pointer))
{
// p is a Derived*
}
else
{
// not the right dynamic type
}
我发现另一个有用的结构:
if (auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(std::fopen("file.txt", "rb"), std::fclose))
{
// file exists, use fp.get()
}
else
{
// file does not exist
}
还有一个:
if (pid_t pid = fork())
{
waitpid(pid, nullptr, 0);
}
else
{
execl("/bin/rm", "/bin/rm", "-rf", "/", static_cast<char*>(nullptr));
}
是的,您可以使用在 else
子语句的 if
条件中声明的变量,就像您的示例一样。
但是,如果在 if
子语句中声明i
,如下所示:
if (some_condition) {
int i = 42;
// ...
} else {
std::cout << i; //error
// ...
}
在else
部分中,变量 i
不再在范围内。
是的,因为变量是在最外层范围内"创建"的,然后才在if
条件下进行评估。您的代码可以重写如下:
int i = SOME_VALUE;
if(i) {
// ...
} else {
// ...
}
而不是像:
if(SOME_VALUE) {
int i = SOME_VALUE;
// ...
} else {
// ...
}
正如你可能有的那样。
第二个问题可以用同样的方式回答。
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象