Realloc等价于C ++ [英] Realloc equivalent in C++
问题描述
是的,另一个 realloc
与 std :: vector
问题。我知道你要说什么,我同意,忘记手动内存分配,只需使用 std :: vector
。很遗憾,我的教授禁止我使用STL中的任何东西来完成这个任务。
所以,我有一个动态数组 T
,我需要它可以调整大小,我不能使用
std :: vector
。我可以回到黑暗的年龄,做整个事情与 malloc
和家庭,但如果我可以使用新
我读过很多线程,每个人都说不,你不能做,使用 std ::向量
,但他们都在2011年8月之前发布,我希望反对希望,自从C ++ 11的黎明以来可能有一些改变。
你应该避免使用 realloc
完全无论如何,因为你不能移动这样的C ++对象。
- 使用
buf = new unsigned char [sizeof(T)* capacity]
创建新缓冲区 - 将分配的
unsigned char *
转换为T *
并从现在起使用这些T
-pointers - 通过placement
new
,如new(& buf [i])T(original_copy)
- 更大的缓冲区,首先分配新的缓冲区,使用
std :: uninitialized_copy
( notstd :: copy
),然后使用buf [i]。〜T()
销毁旧的元素中的元素并使用delete [ ] buf
。
所有这些都假设您不必担心异常安全,
请注意,在现实世界的代码中,你必须保证异常安全,这是一个比这更加乏味。 p>
Yes, another realloc
vs. std::vector
question. I know what you're going to say, and I agree, forget manual memory allocation, and just use a std::vector
. Well unfortunately my professor has forbidden me to use anything from the STL for this assignment.
So yeah, I have a dynamic array of T
and I need it to be resizable, and I can't use std::vector
. I could return to the dark ages and do the whole thing with malloc
and family, but if I could use new
that would be totally awesome.
I've read plenty of threads where everyone said "no, you can't do it, use std::vector
", but they were all posted before August 2011, and I'm hoping against hope that something might have changed since the dawn of C++11. So tell me, am I in luck, or do I have to revert to C style memory allocation?
You should avoid realloc
completely anyway, because you can't move around C++ objects like that.
- Use
buf = new unsigned char[sizeof(T) * capacity]
to create a new buffer - Cast the allocated
unsigned char *
toT *
and use theseT
-pointers from now on - Construct new elements via "placement
new
", as innew (&buf[i]) T(original_copy)
- To copy the buffer to a larger buffer, allocate the new one first, use
std::uninitialized_copy
(notstd::copy
), then destroy the elements in the old one usingbuf[i].~T()
and deallocate the old buffer usingdelete [] buf
.
All of this is assuming you don't have to worry about exception-safety, which is probably OK for the assignment.
Just be aware that in real-world code you'd have to guarantee exception safety and it's a lot more tedious than this.
这篇关于Realloc等价于C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!