2

I'm creating a self initializing arrays class in C++ and I'm wondering how I'd throw an error not an exception if a user were to try and allocate more than 0x7fffffff bytes.

Similar to <array> where:

error C2148: total size of array must not exceed 0x7fffffff bytes

This is my code for one of my constructor where I'm testing this:

    template<typename T>
    Array<T>::Array(const size_t _SIZE) : _SIZE(_SIZE), _content(nullptr){
        #define __SIZE__ _SIZE
        #if (__SIZE__ > 0x7fffffff)
             #error Total size of Array must not exceed 0x7fffffff bytes.
        #endif
        _content = new T[_SIZE];
        memset(_content, 0, (sizeof(_content) * _SIZE));
    }

The way that I'm creating the array is below:

Array<int> foo(-1) //-1 of size_t = ((2^31)*2)-1 error should be shown since ((2^31)*2)-1 > ((2^31)*2)-1

size_t's max size is ((2^31)*2)-1 and 0x7fffffff is (231)-1 now the issue is that the error isn't executing I've never used the #if macro before and I need to get this to work...

Any help would be appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 1
    I believe the memset line should look like this: memset(_content, 0, (sizeof(T) * _SIZE)); – user1764961 May 15 '13 at 06:46
  • 1
    Don't use identifiers that have double underscores or start with underscore followed by a capital. Those are reserved for the implementation (besides from looking ugly anyways), even if used before compilation. – Arne Mertz May 15 '13 at 06:56
  • @user1764961 Or `sizeof(*_content)`. However, it `T` is not a primitive type, then `memset` should not be used at all, since it can to bad things to objects data, including the virtual table if the class have virtual function. – Some programmer dude May 15 '13 at 07:03
  • 1
    By the way, how is you class different from e.g. `std::vector`? You can set both the size and the initial data when [constructing](http://en.cppreference.com/w/cpp/container/vector/vector) a `std::vector`. – Some programmer dude May 15 '13 at 07:05

2 Answers2

3

You can't use the preprocessor for variables. The preprocessor is a separate step that is run before the compilation, and it has no idea about the variables used in the source and especially their run-time values.

For this you might want to use assert:

assert(_SIZE <= 0x7fffffff);

If you pass a negative value to a function expecting unsigned values then you should get a compiler warning, and if not then you should enable more warnings.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

#error is a preprocessor directive. As such, it is executed by the preprocessor during compilation. It cannot check what value is passed as _SIZE parameter because that value is only know when your programm is being executed.

Use some other means to signal errors during run time, e.g. exceptions.

Oswald
  • 31,254
  • 3
  • 43
  • 68