C 通过参考分配 /数组传递内存

C++ pass memory allocated / array by reference

本文关键字:数组 内存 分配 参考      更新时间:2023-10-16

已解决

我正在为处理struct bwords的现有lib编写一个接口(请参见下面的代码),并希望提供在bword本身或字符串字符串(a bword成员)上调用某些检查功能的可能性:

#include <cstdio> 
typedef unsigned char byte;
typedef unsigned short ushort;
typedef struct bwordSt { ushort nbLetters;  byte *L; } bword;
template<typename T, size_t N>
  ushort checkBwL(T (&wL)[N], ushort wSz) {
  return 0;
}
ushort checkBwL(const byte* const &wL, ushort wSz) {
  return 0;
}
ushort checkBw(const bword &bw) {   
  return checkBwL(bw.L, bw.nbLetters);  
}
int main() {
  ushort n;
  byte fL[2] = {0, 1};
  n = checkBwL(fL, 2);  // calls the template function
  bword bW = {2, new byte[3]};
  bW.L[0] = 0; bW.L[1] = 1; bW.L[2] = 2; 
  n = checkBwL(bW.L, 3);  // calls the non-template function
  n = checkBw(bW);        // calls the non-template function
  return n;
}

字符串的字符串可能很大,因此我想通过参考。我做到了。

我发现提供均匀界面的唯一方法是在模板(用于数组[字节])中复制基本检查功能的代码(checkbwl)和一个过载(for byte*),这很丑陋,强制强制我要维持两个基本相同(大)的功能。

有什么方法?

解决方案

无需模板功能,请不要在参数规范中的&之前忘记const const byte* const &wL

成功的关键是委托:

#include <cstdio> 
typedef unsigned char byte;
typedef unsigned short ushort;
typedef struct bwordSt { ushort nbLetters;  byte *L; } bword;
ushort check_impl(ushort length, const byte* buffer)
{
    // do your actual checking here
    return 0;
}
template<typename T, size_t N>
auto checkBw(T (&wL)[N], ushort wSz) -> ushort
{
    return wSz == (N * sizeof(T)) &&  // assuming no null terminator 
    check_impl(wSz, reinterpret_cast<const byte*>(wL));
}
ushort checkBw(const byte* const &wL, ushort wSz) {
  return check_impl(wSz, wL);
}
ushort checkBw(const bword &bw) {   
  return check_impl(bw.nbLetters, bw.L);  
}
int main() {
  ushort n;
  byte fL[2] = {0, 1};
  n = checkBw(fL, 2);  // calls the template function
  bword bW = {2, new byte[3]};
  bW.L[0] = 0; bW.L[1] = 1; bW.L[2] = 2; 
  n = checkBw(bW.L, 3);  // calls the non-template function
  n = checkBw(bW);        // calls the non-template function
  return n;
}