Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - 为什么std :: vector没有释放方法?(Why std::vector does not have a release method?)

I found myself in a situation where I would have liked to have an analog of unique_ptr 's release() for std::vector<> . (我发现自己想在std::vector<>上使用unique_ptrrelease()类似。) Eg: (例如:)

std::vector<int> v(SOME_SIZE);

//.. performing operations on v

int* data = v.release(); // v.size() is now 0 and the ownership of the internal array is released
functionUsingAndInternallyDeletingRowPointer(data);

Is there a particular reason why this kind of possibility is not provided? (为什么没有提供这种可能性的特定原因?) May that impose some constraint on std::vector 's the internal implementation? (这可能会对std::vector的内部实现施加一些约束吗?)

Or there is a way to achieve this that I am embarrassingly missing? (还是有一种方法让我尴尬地错过了?)

  ask by Emerald Weapon translate from so

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

1 Answer

0 votes
by (71.8m points)

functionUsingAndInternallyDeletingRowPointer (functionUsingAndInternallyDeletingRowPointer)

And what exactly would this function do? (而这个功能到底会做什么?) Because that memory was allocated by calling std::allocator_traits<std::allocator<T>>::allocate , which expects it to be deleted by calling std::allocator_traits<std::allocator<T>>::deallocate . (因为该内存是通过调用std::allocator_traits<std::allocator<T>>::allocate ,所以它期望通过调用std::allocator_traits<std::allocator<T>>::deallocate来删除它。) Furthermore, each element of the vector was constructed with a call to std::allocator_traits<std::allocator<T>>::construct , and therefore must be destroyed by a call to std::allocator_traits<std::allocator<T>>::destroy . (此外, vector每个元素都是通过调用std::allocator_traits<std::allocator<T>>::construct ,因此必须通过调用std::allocator_traits<std::allocator<T>>::destroy来销毁。 std::allocator_traits<std::allocator<T>>::destroy 。)

If that function tries to do delete [] on that pointer, it won't work. (如果该函数试图对该指针执行delete [] ,则它将无法正常工作。) Or at the very least, it isn't required to work. (或至少不需要工作。)

It might be reasonable to be able to extract a memory buffer from a vector and use it directly. (能够从vector提取内存缓冲区并直接使用它可能是合理的。) But it could not be a mere pointer. (但这不能仅仅是一个指针。) It would have to have an allocator along with it. (它必须具有一个分配器。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...