提问者:小点点

使用引用作为数组/指针是合法的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++,即是否保证指向数组引用的指针指向原始数组?

有什么理由可以这样做,而不是直接使用指针,而不是将引用作为中间的引用?


共1个答案

匿名用户

我的团队(包括我自己)是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*double*,C++有意希望您使用更详细的const_cast来丢弃const-ness。

如果您希望使用C++“全面”,可以使用模板使the_cpp_wrapper()更通用一些:

template<typename TSpan>
void the_cpp_wrapper(const TSpan& v)
{
   the_c_function(v.data(), v.size());
}

使用此代码,您可以将任何内容传递给具有data()size()方法的_cpp_wrapper。(请注意,tspan“可以”为std::span,这可能会导致一些晦涩难懂的编译器错误;有一些方法可以修复,但更多的是C++。)

与您的具体问题没有直接关系,但您可能会发现std::span也很有用。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(引用|数组|指针|合法|c++)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?