sli*_*aap 3 c++ pointers reference
我的团队(包括我自己)是 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;
}
Run Code Online (Sandbox Code Playgroud)
编译后,它按预期工作:它打印数组的内容:
0: 3
1: 4
2: 5
3: 6
Run Code Online (Sandbox Code Playgroud)
但这对我来说几乎不合法,或者最好是应该劝阻的事情。
这是合法的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;
}
Run Code Online (Sandbox Code Playgroud)
您还应该更清楚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());
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,您可以将任何内容传递给the_cpp_wrapperhasdata()和size()方法。(请注意,TSpan“can”std::span<int>可能会导致一些晦涩的编译器错误;有办法解决这个问题,但更多的是 C++。)
没有直接关系,但您可能也会发现它std::span很有用。