简体   繁体   English

C++ vector at(#) 替换清理内存?

[英]C++ vector at(#) replacement clean up memory?

The pains of compiled libraries is never knowing exactly how the memory is managed.编译库的痛苦是永远不知道内存是如何管理的。 I'm lead to believe that vector's elements are placed on the heap unless explicity told not to.我相信向量的元素被放置在堆上,除非明确告诉不要。

Being placed on the heap, it obviously needs to be deleted when it is no longer used, which seems to happen when the vector object is deleted.放在堆上,显然不再使用时需要删除,这似乎是在删除vector对象时发生的。

The question is when the at(#) or operator[] is called does it delete the memory being replaced?问题是当 at(#) 或 operator[] 被调用时,它会删除被替换的内存吗?

For example:例如:

std::vector<string> secretlyAnArray(5);
secretlyAnArray.at(0) = std::string("Does this memory leak?");
secretlyAnArray.at(0) = std::string("When I overwrite the object?")

Happy to learn better methods to replace data at a specific index of a vector, or just pointing at the documentation that explains it.很高兴学习更好的方法来替换向量特定索引处的数据,或者只是指向解释它的文档。

Edit: After the helpful comments of Anis and Daniel;编辑:在 Anis 和 Daniel 的有益评论之后; Is it correct in saying that:是否正确的说法是:

// Given: 
secretlyAnArray.at(0) = std::string("Does this memory leak?");

// This will call the equavant code of for an L value:
string::operator=(const std::string& other)

//Given
secretlyAnArray.at(0) = std::move(std::string("Does this memory leak?"));

//This will call the equavalent code for an R value:
string::operator=(const std::string&& other)
std::vector<std::string> secretlyAnArray(5);
secretlyAnArray.at(0) = std::string("Does this memory leak?");
secretlyAnArray.at(0) = std::string("When I overwrite the object?")

This code assigns an object of type std::string to another object of type std::string .此代码受让人类型的对象std::string到类型的另一个对象std::string The std::vector itself isn't at all involved in this assignment. std::vector本身根本不参与此分配。 Here, it just provides a reference to the destination (assigned-to) object.在这里,它只提供对目标(分配给)对象的引用。

What does assignment do for a given type depends on its definition.赋值对给定类型的作用取决于它的定义。 There is no generic answer.没有通用的答案。 For instance, with std::string , when you copy/move-assign, the original content of the destination object (its string of characters) needs to be "destroyed".例如,对于std::string ,当您复制/移动分配时,需要“销毁”目标对象(其字符串)的原始内容。 std::string does it for you, so, you don't need to care about it. std::string为你做这件事,所以,你不需要关心它。 It means that if the string is "long" (with regard to short string optimization ; SSO), the memory will be correctly deallocated, if needed.这意味着如果字符串是“长”(关于短字符串优化;SSO),如果需要,内存将被正确释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM