问题描述
在C中,我们使用malloc(), free()
,但是在C ++中,您正在使用new, delete
,但是在C中,我们也具有realloc
,它将分配新块并复制旧数据(最小的公共数据),然后释放旧数据数据框.那么,那是什么C ++版本?我当然可以自己写,但是有内置的东西吗?
In C we used malloc(), free()
, but in C++ youare using new, delete
, but in C we also have realloc
, which will alloc the new block and copy the old data (common minimum) and then free the old data bock. So what is the C++ version of that? I can write my own of course, but is there a builtin thing?
main() {
int i; char *x = malloc(3);
x[0] = 10;
x[1] = 20;
x[2] = 30;
realloc(x, 4);
x[3] = 40;
for (i = 0; i < 4; i++) printf("%i\n", x[i]);
}
推荐答案
在C ++中,没有new
/delete
等效于realloc
.
There's no new
/delete
equivalent of realloc
in C++.
如果愿意,您当然可以使用realloc().但是,realloc()是 仅保证在malloc()分配的数组上工作(和类似的) 函数)包含没有用户定义的副本构造函数的对象. 另外,请记住与天真期望相反,realloc() 偶尔会复制其参数数组.在C ++中,更好的方法是 处理重新分配是使用标准库容器,例如 作为载体,并使其自然生长.
If you want to, you can of course use realloc(). However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occasionally does copy its argument array. In C++, a better way of dealing with reallocation is to use a standard library container, such as vector, and let it grow naturally.
如果您想要一个可调整大小的容器,只需使用std::vector
,否则使用malloc
,realloc
和free
.
If you want a resizeable container, just use std::vector
, otherwise stay with malloc
, realloc
and free
.
然后,要回答您的最后一个问题,您的代码的C ++版本将为:
And, to answer your last question, the C++ version of your code would be :
main() {
std::vector<char> x(3);
x[0] = 10;
x[1] = 20;
x[2] = 30;
x.resize(4);
x[3] = 40;
for (int i = 0; i < 4; i++) std::cout << x[i] << std::endl;
}
这篇关于分配新缓冲区并复制旧缓冲区的内容的realloc()的C ++版本是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!