c++ stl复制功能正确的内存管理
就在下面的代码中,我是否需要使用 new 为 floatArray 分配内存,还是复制函数会为我分配内存?
另外,可以通过这种方式将常量向量复制到数组吗?为什么?
vector<float> floatVector;
//filled floatVector here
float *floatArray = new float[floatVector.size()];
copy(floatVector.begin(),floatVector.end(),floatArray);
delete[] floatArray;
Just on the following code do I need to allocate memory with new for floatArray or will the copy function allocate memory for me?
Also is it okay to copy a constant vector to an array this way? Why?
vector<float> floatVector;
//filled floatVector here
float *floatArray = new float[floatVector.size()];
copy(floatVector.begin(),floatVector.end(),floatArray);
delete[] floatArray;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
std::copy
不分配内存,您应该自己分配内存。std::copy
doesn't allocate memory, you should do it yourself.如果您不想先分配数组,那么您可以使用 back_inserter 迭代器将元素一个接一个地推送到某些容器中。对于某些容器来说,这效率较低(我认为),但有时非常方便。
If you don't want to allocate the array first then you may use a
back_inserter
iterator to push elements one by one into certain containers. For some containers this is less efficient (I think) but can be very handy sometimes.copy 不会为您分配,所以是的,您需要分配它。
copy will not allocate for you, so yes you need to allocate it.
std::copy 使用参数赋值(“=”)运算符或参数复制构造函数进行复制(这可能取决于实现,我现在不确定)。它什么也不做,只是迭代从 param.begin() 到 param.end() 的范围并执行以下操作:
因此,您需要自己分配必要的内存。否则会产生未定义的行为。
以这种方式将常量向量复制到数组可以吗?取决于你想做什么。一般来说,这很好,因为值是按值而不是按引用传输到目标的,因此常量正确性不会被破坏。
例如,这工作正常:
std::copy copies by using the arguments assignment ("=") operator or the arguments copy constructor (this is probably implementation dependent, I'm not sure right now). It does nothing but iterate through the range beginning at param.begin() to param.end() and do something like:
Thus, you need to allocate the memory necessary yourself. Otherwise it will create undefined behaviour.
Is it OK to copy a constant vector to an array this way? Depends on what you want to do. Generally, it's fine, since the values are transferred to the target by value, not by reference, hence const-correctness is not broken.
For example, this works fine:
复制函数从不分配内存,但您必须为静态数据结构分配内存,但对于动态数据结构,它会自动分配内存。
这个过程不好,但最好使用另一个向量而不是 floatarray
copy function never allocate memory but you have to allocate memory for static datastructures but for dynamic datastructures, it'll allocate memory automatically.
and this process is not good but its better to use another vector instead of that floatarray