Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a C-style array without calling default constructors?

I am writing a memory-managing template class in which I want to create a C-style array of fixed size, to serve as a heap. I keep the objects stored in an array like this:

T v[SIZE];

As this only serves the role as a heap that can hold T objects, I don't want the T default constructor to get automatically called for every object in the array.

I thought about the solution to define the heap like this:

char v[SIZE * sizeof(T)];

...but this will give me alignment problems.

Is there any better way to achieve this?

ADD: As I have special run time requirements, it is essential that this class doesn't do any allocations on the global heap.

ADD 2: SIZE is a template argument and known at compile-time.

like image 293
Johan Kotlinski Avatar asked Feb 16 '10 14:02

Johan Kotlinski


People also ask

Can we create object without calling constructor?

Abstract: De-Serialization creates objects without calling constructors. We can use the same mechanism to create objects at will, without ever calling their constructors.

Can we create an array of objects for a class having default constructor?

You should define it in class CheckBook constructor. Save this answer. Show activity on this post. The correct way to build an array of objects having no default constructor is to use the placement new syntax to separate the allocation of the array and the construction of the objects.

Will default constructor be always called?

This constructor is called the default constructor because it is run "by default;" if there is no initializer, then this constructor is used. The default constructor is used regardless of where a variable is defined.

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members. A constructor of a class A is trivial if all the following are true: It is implicitly defined. A has no virtual functions and no virtual base classes.


1 Answers

The standard containers use allocators to seperate allocation/deallocation from construction/destruction. The standard library supplies a single allocator which allocates on the heap.

This code declares an array big enough to hold SIZE elements of type T with the correct allignment:

typedef typename std::tr1::aligned_storage<sizeof(T),std::tr1::alignment_of<T>::value>::type aligned_storage;
aligned_storage array[SIZE];

The solution using std::allocator can't be used to declare an array on the stack, and as the standard containers require that custom allocators hold no state, a custom allocator can't be portably used to allocate on the stack either.

If your compiler doesn't support std::tr1::alignment_of you can use boost::alignment_of instead.

like image 170
JoeG Avatar answered Sep 19 '22 22:09

JoeG