I have a class A, which has a nested class B. Class A, will create n(run time parameter) instances of class B.
In the constructor of A, after computations that need to be made at run time, I compute a size, let's say s.
Now, every class B, will hold an array of size s.
However, I am not allowed to use .cpp files and all the work must be done in header files.
This means, as far as I understand, that I can not use these approach (with static
):
class B {
static const int s;
int a[s];
};
So, I decided to use enum
, but I couldn't make it work (even with enum class
of C++11).
The idea is that you do something like:
class B {
enum { s = 50 };
int a[s];
};
but I do not know the s
before run time.
Of course, I could go with an std::vector
or with dynamic allocation
.
But since:
1)I need only the functionality of the old good arrays (discards vector)
2)I know before constructing the instances of B, the size of the array (discards dynamic allocation)
About std::dynarray
discussed below:
Unfortunately not in C++14
, but in array TS
or C++17
.
Source, credits to manlio.
Discard is however a heavy word. I mean, I have heard that automatic allocation is faster, but dynamic allocation lets you allocate more space. Moreover, vectors, in the release mode, are doing not that bad in comparison with the arrays.
std::array
if you know the size from compile time? – Logographys
before run time. – Thoroughbredstd::vector
, measure the performance in release build. – Mordaciousstd::vector
and callreserve(s)
as soon ass
is known. Or, you can construct those vectors at sizes
and not change their size after that. – Prestonprestressreserve
is that may reserve more space than what you are asking. @Cheersandhth.-Alf, do not only see it by aspect of performace, see it from aspect of educating. :) – Madalene