Reserve space for array

Oct 12, 2013 at 3:41pm
Hello everyone,

I have an easy question, I think.
In my code I have a template class.
In the contructor, I create a new array arrray.
A pointer to this array is saved as an attribute.
The purpose of this attribute is that I should be able to call the array from within another function be typing *p or *(p+1) etc.
The only thing I forgot is that the array doesn't exist anymore when the constructor is done, right?
This means the space is no longer reserved for this array and the space is used for other things.

Is there a way to keep the array space reserved (even when the array does not exist anymore at the end of the function)?
Oct 12, 2013 at 4:54pm
Use std::vector:
1
2
3
4
5
6
7
8
9
10
class MyClass
{
    std::vector<int> v;
public:
    MyClass(std::size_t size)
    : v(size)
    {
    }
    //...
};
If you cannot use std::vector, use a std::unique_ptr to a dynamically allocated array:
1
2
3
4
5
6
7
8
9
10
class MyClass
{
    std::unique_ptr<int[]> arr;
public:
    MyClass(std::size_t size)
    : arr(new int[size])
    {
    }
    //...
};
If you cannot use std::unique_ptr, use a dynamically allocated array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MyClass
{
    int *p;
public:
    MyClass(std::size_t size)
    : p(new int[size]
    {
    }
    ~MyClass() //you need the destructor to call delete[]
    {
        delete[] p;
    }
    //...
};
Feel free to ask specific questions about each variant.
Last edited on Oct 12, 2013 at 4:56pm
Topic archived. No new replies allowed.