我在函数中声明了许多指向可变长度数组(VLA)的指针来动态分配二维数组;例如,
int M, N; // have some value
double (*arr1)[N] = calloc(M, sizeof(double [N]));
double (*arr2)[N] = calloc(M, sizeof(double [N]));
double (*arr3)[N] = calloc(M, sizeof(double [N]));
... // so many declarations
Run Code Online (Sandbox Code Playgroud)
因为函数变得很长,所以我尝试将其分成几个函数,每个函数都需要所有指针作为参数。我没有在函数中传递许多东西(这对性能不利),而是声明了一个全局包含所有指针的结构,以减少参数数量:
struct ptrpack {
int M, N;
double (*arr1)[N];
double (*arr2)[N];
...
};
// then each function just takes a single struct rather than many pointers
void foo(struct ptrpack p) {
...
}
Run Code Online (Sandbox Code Playgroud)
但是,struct 中不允许存在指向 VLA 的指针。如果结构定义位于函数中,则 GCC 扩展允许这样做,但在我的例子中,定义位于全局范围内。
这个问题的最佳解决方案是什么?我强烈喜欢使用指向 VLA 的指针,而不是普通的指针。
如果std::uninitialized_copy用于初始化的内存,这种使用是否会导致内存泄漏或未定义的行为?
例如:
std::vector<std::string> u = {"1", "2", "3"};
std::vector<std::string> v = {"4", "5", "6"};
// What happens to the original elements in v?
std::uninitialized_copy(u.begin(), u.end(), v.begin());
Run Code Online (Sandbox Code Playgroud)