gpt4 book ai didi

C++ static_cast 从 float** 到 void**

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:09 29 4
gpt4 key购买 nike

刚遇到这个:

#include <iostream>

using namespace std;

int main(int argc, char** argv)
{
float *a = new float[10];
void **b;
b = static_cast<void**>(&a);
delete(a);
return 0;
}

macbook:C nils$ g++ -Wall -g -o static_cast static_cast.cpp
static_cast.cpp: In function ‘int main(int, char**)’:
static_cast.cpp:9: error: invalid static_cast from type ‘float**’ to type ‘void**’
macbook:C nils$ clang++ -Wall -g -o static_cast static_cast.cpp
static_cast.cpp:9:9: error: static_cast from 'float **' to 'void **' is not
allowed
b = static_cast<void**>(&a);
^~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
macbook:C nils$

为什么不允许?而 b = (void**)(&a);作品。

最佳答案

$5.2.9/2 -

"An expression e can be explicitly converted to a type T using a static_cast of the form static_cast(e) if the declaration “T t(e);” is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The result is an lvalue if T is a reference type (8.3.2), and an rvalue otherwise. The expression e is used as an lvalue if and only if the initialization uses it as an lvalue."

让我们以代码片段 1 为例

float *f;

void *p = f;

这里 'p' 的初始化是合式的。这符合$4.2

“指向 cv T 的指针”类型的右值,其中 T 是对象类型,可以转换为“指向 cv void 的指针”类型的右值。

现在让我们把代码放到OP中

在我们的例子中,“E”是“float **”,“T”是“void **”

因此,如果可以如下所示初始化“p”,那么 static_cast 是否适用于尝试的转换

float **f;

void **p = f;

“p”的初始化格式错误,因为它不是 $4.10 下列出的有效条件

现在,来看看为什么 b = (void**)(&a); 有效?

这是使用显式转换的情况 ($5.4)。在这种情况下,此显式转换等效于 reinterpret_cast ($5.4/5)。在这种特殊情况下,这种转换是允许的 ($5.2.1/7)。

这有帮助吗?

关于C++ static_cast 从 float** 到 void**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3625410/

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