Dynisious
Dynisious

Reputation: 46

Allocating and deallocating memory c++

I'm trying to implement an array class which can be dynamically sized and it will allocate memory without initialising values. My question is relating to how I deallocate the memory later:

Can I implement my code in this way?:

template<typename Type>
class Array {
    Type *values;

    Array(int size) : values(new (size * sizeof(Type)) char()) {}
    ~Array() {
        delete[] values;
    }
}

Or will I need something like this?:

template<typename Type>
class Array {
    Type *values;
    void *memory;

    Array(int size) : memory(new (size * sizeof(Type)) char()), values(memory), size(size) {}
    ~Array() {
        delete[] memory;
    }
}

NOTE!!!! I am aware that this will allocate memory without initialising any Type objects. This is the intended behavior of my code. Also the code above is not my complete implementation, it's only the code that will allocate and deallocate the memory because that is what I'm interested in with this question.


Upon further research I found that I should use malloc() and free() to do what I'm trying to do. Thank you to all answers and commenters.

Upvotes: 1

Views: 127

Answers (2)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

You can use a Type* to make life easier, and use operator new to get memory without constructing objects.

Type* values; //No aliasing/casting issues
Array(int size) : values((Type*)::operator new(sizeof(Type) * size)) //...
~Array() { /*clean up extant objects*/ ::operator delete(values); }

Then you can use placement new and explicit destructor calls to manage the elements. Also, placement new doesn't allocate memory. It constructs an object at the specified address.

Upvotes: 2

o11c
o11c

Reputation: 16016

Placement new does not actually allocate any memory. It is merely syntax for calling a constructor with already-allocated memory.

In your destructor, you must manually call the destructors for each present element, then deallocate the memory in the same way it was allocated. Be very careful about exceptions.

You should probably use std::allocator<T>::allocate and std::allocator<T>::deallocate, but you could use malloc/free, new char[]/delete[] (char*)arr, or ::operator new/::operator delete.

Upvotes: 1

Related Questions