簡體   English   中英

C ++通過引用分配內存/數組

[英]C++ pass memory allocated / array by reference

解決了

我正在向處理struct bwords的現有庫編寫接口(請參見下面的代碼),並希望提供對bword本身或字節串(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;
}

字節字符串可能很大,因此我想引用引用。 而我做到了。

我發現提供統一接口的唯一方法是在模板(針對arrays [byte])和重載(針對byte *)中復制基本檢查功能(checkBwL)的代碼,這很丑陋,迫使我進行維護兩個基本相同(大)的功能。

可以解決嗎?

無需模板功能,只是不要忘了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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM