C 通过参考分配 /数组传递内存
C++ pass memory allocated / array by reference
已解决
我正在为处理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;
}
相关文章:
- unordered_map 与地图与数组 - 内存分析
- 字符指针数组内存分配
- SystemC sc_signal数组内存边界
- 在分配指向数组内存地址的指针时,为什么不必使用地址运算符?
- 指向结构的指针的 2D 数组.内存访问问题
- 连接数组,数组 1 内存消失C++
- 无法使用 GetProcessMemoryInformation 测量静态数组内存使用情况
- 2D 数组内存分配 (malloc) 返回 NULL
- 删除指针成员变量的数组内存
- C++类数组内存重新分配
- 处理静态数组内存C++的内存不足情况
- 为什么析构函数不释放数组内存?
- 获取 std::array 底层数组内存大小的最简单方法?
- C 4D数组内存Deallocation速度很慢
- char*数组内存泄漏
- 数组内存地址总是按最小到最大的顺序排列吗
- C++中的Char*数组内存分配
- 动态数组内存分配如何工作
- JNA 本机函数调用和具有双**指针/数组内存分配的结构
- 了解字符数组内存分配