macros - How to use the #error directive - C++ -
i'm creating self initializing arrays class in c++ , i'm wondering how i'd throw error not exception if user try , allocate more 0x7fffffff
bytes.
similar <array>
where:
error c2148: total size of array must not exceed 0x7fffffff bytes
this code 1 of constructor 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 i'm creating array below:
array<int> foo(-1) //-1 of size_t = ((2^31)*2)-1 error should shown since ((2^31)*2)-1 > ((2^31)*2)-1
size_t
's max size ((2^31)*2)-1
, 0x7fffffff
(231)-1 issue error isn't executing i've never used #if
macro before , need work...
any appreciated.
you can't use preprocessor variables. preprocessor separate step run before compilation, , has no idea variables used in source , run-time values.
for might want use assert
:
assert(_size <= 0x7fffffff);
if pass negative value function expecting unsigned values should compiler warning, , if not should enable more warnings.
Comments
Post a Comment