English 中文(简体)
矢量: 清除/ 后背将无法运行毁灭器
原标题:Vector:clear/pop_back won t run destructor

我有一个“ Pictureframe” 的矢量( 列表), 我想销毁全部 。 所以我运行 pflist. clear () ; 文件上说, 它运行着矢量中每个物品的毁灭器, 但是它不是!

我有:

vector<Pictureframe*> pflist;

其余的是:

class Pictureframe{
    scene::IMeshSceneNode *picture;
    scene::IMeshSceneNode *frame;

public:
    Pictureframe();
    ~Pictureframe();
};

然后在 cpp 文件 中 :

Pictureframe::~Pictureframe(){
//  delete picture;
//  delete frame;
    cout<<"Destructor Called.

";
}

看见一个叫"破坏者"的纳里!

pflist.clear();

我确信这条线正在运行, 并有5幅图框。 我也尝试过一条环绕线, 穿过矢量的回流, 并且也有同样的问题 。

破坏者,不打电话吗?

最佳回答

您的问题没有说明 std:: victor 是什么类型。 如果该类型是 < code>std:: victor & lt; Picturderam {gt; , 那么当您调用 < code> std::: clear 时, 每一个元素的破坏器将不会被调用。 在这种情况下, 您有责任将这些对象 < strengen@ em > 之前的 < em{/ strong> 清除矢量 。

如果您不需要动态分配这些对象, 请将矢量类型更改为 std:: victor< Pictureframe> 。 使用它为 :

std::vector<Pictureframe> vec;
vec.push_back( Pictureframe( ... ) );
// do stuff
vec.clear();

现在每个对象的毁灭器将被调用。 记住要为 < code> Pictureframe < / code > 创建一个复制构建器和指派操作员, 因为看起来该类正在管理一些资源 。

如果您必须动态分配 Pictureframe 对象, 请将矢量更改为

std::vector<std::unique_ptr<Pictureframe>> vec;
vec.push_back( std::unique_ptr<Pictureframe>( new Pictureframe( ... ) ) );
// do stuff
vec.clear();

unique_ptr 将自动 delete 这里的对象。

其他替代办法有boost::共享_ptr 而不是std: unique_ptr boust::ptr_vector 。

问题回答




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?