Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

dynamic memory allocation - Realloc equivalent in C++

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 * to T * and use these T-pointers from now on
  • Construct new elements via "placement new", as in new (&buf[i]) T(original_copy)
  • To copy the buffer to a larger buffer, allocate the new one first, use std::uninitialized_copy (not std::copy), then destroy the elements in the old one using buf[i].~T() and deallocate the old buffer using delete [] 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...