user542687
user542687

Reputation:

C++: Array with custom size in class

I want to do this:

class Graphic
{
    int *array;
    Graphic( int size )
    {
        int temp_array[size];
        array = temp_array;
        glGenTextures( size, array );
    }
}

Will this work? And even if it will, is there a better way to do this?

Thanks.

Upvotes: 2

Views: 3177

Answers (2)

j_random_hacker
j_random_hacker

Reputation: 51256

Using new means you have to remember to delete [] it; using compiler-dependent variable-size arrays means you lose portability.

It's much better to use a vector.

#include <vector>

class Graphic
{
    std::vector<int> array;
    Graphic( int size )
    {
        array.resize(size);
        glGenTextures( size, &array[0] );
    }
}

The language guarantees that vector elements will be contiguous in memory so it's safe to do &array[0] here.

Upvotes: 8

sashang
sashang

Reputation: 12214

No, the memory for temp_array is allocated on the stack. When the function ends then that memory is deallocated and all you'll be left with is a dangling pointer. If you want to keep the array valid beyond the point that the constructor returns then allocate it dynamically using new. Example:

array = new int[size]

And then remember to delete it. Typically this is done in the destructor like this:

delete[] array

Upvotes: 1

Related Questions