Search code examples
c++classvectorpush-back

C++ vector of class objects and dynamic memory allocation


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;
}


Solution

  • Here's a working code: 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;
    }
    

    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.