类对象和动态内存分配的 C++ 向量 [英] C++ vector of class objects and dynamic memory allocation

查看:39
本文介绍了类对象和动态内存分配的 C++ 向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要做的简化版本,它在调用 push_back 时崩溃,特别是在调用析构函数时.如果我删除析构函数的主体,它可以工作,但我想确保它被删除.我尝试使用 new/delete 代替 calloc/free,结果相同.我在这里做错了什么?

This is a simplified version of what I want to do, it crushes when push_back is called, specifically when the destructor is called. If I delete the body of the destructor it works, but I want to be sure that it is deleted. Instead of calloc/free I tried new/delete with the same result. What do I do wrong here?

#include <cstdlib>
#include <vector>


using namespace std;

class Buffer
{
public:
    float *DATA;

    Buffer(int length) {DATA = (float*) calloc (length,sizeof(float));};
    virtual ~Buffer(){free (DATA);};
    
private:
};

int main(int argc, char** argv)
{
    vector <Buffer> v;
    for (int i =0; i<10; i++)
        v.push_back(Buffer(1000));
    
    return 0;
}

推荐答案

这是一个工作代码:https://Godbolt.org/z/ex9oMG.

#include <cstdlib>
#include <vector>

using namespace std;

class Buffer
{
public:
    float *DATA;

    Buffer(int length) {DATA = (float*) calloc (length,sizeof(float));};
    Buffer(const Buffer &buffer) = delete;
    Buffer(Buffer&& buffer) { 
        DATA = buffer.DATA;
        buffer.DATA = nullptr;
    }
    ~Buffer(){
        if (DATA) free(DATA);
    };
    
private:
};

int main(int argc, char** argv)
{
    vector <Buffer> v;
    for (int i =0; i<10; i++)
        v.push_back(Buffer(1000));
    return 0;
}

你需要在这里定义一个移动构造函数,主要是因为v.push_back(Buffer(1000))需要一个移动操作,否则删除原始副本会释放资源.

You need to define a move constructor here, primarily because v.push_back(Buffer(1000)) requires a move op otherwise the deletion of the original copy would free the resource.

我已经明确删除了复制构造函数,因为在处理此类资源时 - 不应允许复制.

I've explicitly deleted the copy ctor because when handling such resources - copy should not be allowed.

这篇关于类对象和动态内存分配的 C++ 向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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