从指针转换为 c 数组引用?

问题描述 投票:0回答:1

是否可以将分配的内存转换为对 c 数组的引用而不调用未定义的行为?

我在堆中有 4 个元素,希望将其视为 2x2 c 数组(例如传递给函数)。 我在这里使用

reinterpret_cast
。还有其他比
reinterpret_cast
更温和的事情我可以做吗?

// Type your code here, or load an example.
double f(double(&ref)[2][2]) {
    return ref[0][0] + ref[1][1];
}


int main() {
    double* data = new double[4];
    data[0] = 1; data[1] = 1; data[2] = 1; data[3] = 1;

    auto& array = reinterpret_cast<double(&)[2][2]>(*data);
//  auto& array = *reinterpret_cast<double(*)[2][2]>(data);

    f(array);
    delete[] data;
}

https://godbolt.org/z/84Kxjoqjq

clang-tidy 明确建议不要使用

reinterpret_cast

Sonar Lint 表示使用

reinterpret_cast
是未定义的行为。

dereference of type 'double *[2][2]' that was reinterpret_cast from type 'double *' has undefined behavior

c++ arrays pointers reference reinterpret-cast
1个回答
0
投票

如果您的目标是抑制 clang-tidy C++ 核心指南诊断,那么您可以通过转换为

void*
来破解它。 这是取自 C 规则的肮脏伎俩。

double f(double (&ref)[2][2]) {
  return ref[0][0] + ref[1][1];
}

int main() {
  double* data = new double[4]{1, 1, 1, 1};

  auto& array = *static_cast<double(*)[2][2]>(static_cast<void*>(data));

  f(array);
  delete[] data;
}

https://godbolt.org/z/rd97P4TM7

© www.soinside.com 2019 - 2024. All rights reserved.