vector::erase() 也擦除结构的成员向量 [英] vector::erase() also erases member-vectors of a struct

查看:31
本文介绍了vector::erase() 也擦除结构的成员向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

各位,我对所有这些编程演讲都很陌生.到目前为止,通过谷歌搜索很容易找到答案,但在这里我很难表达我想问的问题,让我试试:在释放内存之前擦除向量调用析构函数,对吗?现在,如果 struct-vector 被破坏,它会如何反应?没有为这些东西定义析构函数,但假设如果一个结构被析构",它的每个成员的析构函数也会被调用是否正确?

People, I am new to all this programming talk. Up until now it was quite easy to find answers by googling them but right here I have big trouble expressing what I want to ask, let me try: Erasing a vector calls the destructor before freeing the memory, right? Now how does a struct-vector react, if it is destructed? One does not define a destructor for these things, but is it correct to assume that if a struct is "destructed" each of its members' destructors will be called as well?

举个例子:

#include <string>
#include <vector>
struct ding_t {
    std::string dang;
} foo;

strung boom_t {
    vector <ding_t> chuck;
} bar;

int main () {
    vector <boom_t> tom;
    tom.resize(10);
    tom[4].chuck.resize(5);
    tom[4].chuck[3].dang = "jerry";
    tom.erase();

    return 0;
}

在这种情况下,将分配的内存

in this case, will the memory allocated by

tom[4].chuck.resize(5);

也被释放了吗?抱歉我的词汇量,但此时我正试图从指针转向更复杂的 cpp 语言等价于向量.我希望我明白我的意思.在此先感谢大家,如果有人问过这个问题,请给我重定向,正如我所说,我不知道如何限制这个问题.

be freed as well? Sorry for my vocabulary, but at this moment I am trying to move from pointers to the more sophisticated cpp language equivalent of vectors. I hope I got my point across. Thanks in advance guys and please just redirect me if this has already been asked, as I've said, I don't know how to circumscribe this question.

推荐答案

是的,内存会自动释放.

Yes, the memory will be freed automatically.

当一个向量被析构时,它会调用它包含的所有元素的析构函数.您没有为 struct 定义析构函数,因此编译器将为您提供一个默认的析构函数(什么都不做).

When a vector is destructed it will call the destructor of all the elements it contains. You didn't define a destructor for your struct so the compiler will provide a default one for you (that does nothing).

但是,如果您的向量包含指向对象的指针,则有责任在析构向量之前调用对象的析构函数(因为向量将调用指针的析构函数em>,而不是指向对象),如果您以后没有其他方法可以访问它们.

However if your vector contains pointers to objects it will be your responsibility to call the destructor on the objects before destructing the vector (because the vector will call the destructor of the pointers, not the pointed objects), if you have no other way to access them later.

这篇关于vector::erase() 也擦除结构的成员向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆