Reputation: 107
I want to create an array of objects with non-default Constructor. Please note that I am not allowed to use vector from STL, I made a research on this and found a method:
Obj* p_obj[3];// for an array of 3 for example
// then allocate to each pointer using new
p_obj[0] = new Obj(10);
p_obj[1] = new Obj(15);
p_obj[2] = new Obj(20);
though when I am trying to create a bigger array(100 elements), my program goes segFault. I would appreciate if someone would advice me a good solution for this problem.
Thank you in advance!
Upvotes: 0
Views: 231
Reputation: 7844
First of all, your code is completely correct. If it crashes, it must be a memory error elsewhere.
Second, your code is inefficient by allocating so many small objects individually and use double indirection. The key to how vector works (by default) is placement new. Example usage:
Obj* objects = static_cast<Obj*>(operator new(sizeof(*objects) * n));
for (size_t i = 0; i < n; ++n)
new (objects + i) Obj("Constructor arguments...")
When you delete, you have to manually call the destructor of individual elements before deallocating the storage. That is
for (size_t i = 0; i < n; ++n)
objects[i].~Obj();
operator delete(objects);
It is recommended to use a RAII wrapper to do the above allocation and deallocation.
And besides, why are you not allowed to use vector
from STL?
Upvotes: 1
Reputation: 3049
Well if you can't use vector
struct myVector
{
private:
Obj *p_obj;
std::size_t size_;
public:
myVector(): size_(0)
{
}
/*
myVector(int const &size): size(size_)
{
p_obj = new Obj[size_];
}
*/
~myVector()
{
if(size_ != 0)
{
delete[] p_obj;
}
}
void resize(int const&size)
{
// delete or append new memory
}
void push_back(int const &rhs)
{
// push here, check size and allocate needed memory
}
Obj *begin()
{
// Check size and return first element
}
Obj *end()
{
// Check size and return end element
}
}
This is very basic stuff, you also could use an iterator encapsulation which would save you a lot of headaches.
If this is for class it would be useful to come up with your own vector
based on the vector
functionality.
Upvotes: 0