c++ - c++ 使用引用作为数组/指针是否合法?
问题描述
我的团队(包括我自己)是 C++ 新手。我们新开发的一部分是一个 C++ 函数,它需要与一个将数组作为输入的 C 函数接口。为了实现这一点,制作了类似以下构造的东西:
#include "stdio.h"
void the_c_function(double *array, int len)
{
for (int i = 0; i < len; i++)
{
printf("%d: %g\n", i, array[i]);
}
}
void the_cpp_wrapper(double& dref, int len)
{
the_c_function(&dref, len);
}
int main()
{
const int LEN = 4;
double dbl_array[LEN] = { 3,4,5,6 };
the_cpp_wrapper(dbl_array[0], LEN);
return 0;
}
编译后,它按预期工作:它打印数组的内容:
0: 3
1: 4
2: 5
3: 6
但这对我来说几乎是不合法的,或者充其量是应该劝阻的。
这是合法的 C++,即它是否保证指向数组引用的指针指向原始数组?
有什么理由为什么要这样做而不是直接使用指针而不是在中间使用引用?
解决方案
我的团队(包括我自己)是 C++ 新手。...
[...]
......应该劝阻的事情。
您现在应该养成使用标准 C++ 库的习惯,在您的情况下,最好的选择是std::vector
:
#include <stdio.h>
#include <stdlib>
#include <vector>
void the_c_function(const double *array, size_t len) {/*...*/}
void the_cpp_wrapper(const std::vector<double>& v)
{
the_c_function(v.data(), v.size());
}
// ----------------------------
int main()
{
const std::vector<double> dbl_array { 3,4,5,6 };
the_cpp_wrapper(dbl_array);
return EXIT_SUCCESS;
}
您还应该更清楚const double*
vs. double*
,C++ 故意希望您使用更冗长const_cast<double*>
的方式来抛弃const
-ness。
如果您想使用 C++“全力以赴”,您可以the_cpp_wrapper()
使用模板进行更通用的操作:
template<typename TSpan>
void the_cpp_wrapper(const TSpan& v)
{
the_c_function(v.data(), v.size());
}
使用此代码,您可以将任何内容传递给the_cpp_wrapper
hasdata()
和size()
方法。(请注意,TSpan
“can”std::span<int>
可能会导致一些晦涩的编译器错误;有一些方法可以解决这个问题,但它更像是 C++。)
不直接相关,但您可能也会发现std::span
有用。
推荐阅读
- javascript - Vuejs 从头部隐藏样式标签 | Laravel-vuejs 应用程序
- python - 将视图中的函数转换为异步函数。django/python
- python - 如何更改 Odoo 10 中的“oe_chatter”日志评论?
- angular - 首次应用渲染后延迟模块预加载
- powershell - powershell base64编码不同的结果
- python - 如何在 SymPy 中使用 nonlinsolve 返回有限(浮点)值?
- typescript - 如何在没有冲突的情况下将 Mocha 和 Jest 与 TypeScript 一起使用?
- amazon-web-services - 在 AWS Lambda 中运行 selenium 测试 (chrome) - NET Core
- angular7 - 如何修改从 observable 获取的数据?
- ansible - 如何避免类型转换警告?