Declare a fixed-length array in nested classes

I have a class A that has a nested class B. Class A will create n (runtime parameter) of class B.

In constructor A, after the calculations that need to be performed at runtime, I calculate the size, say, s.

Now each class B will contain an array of size s.

However, I am not allowed to use .cpp files, and all work must be done in the header files.

This means, as far as I understand, that I can not use this approach (c static):

class B {

static const int s;
int a[s];

};

So, I decided to use enum, but I could not get it to work (even with enum classC ++ 11). The idea is that you are doing something like:

class B {

enum { s = 50 };
int a[s];

};

but I don't know suntil runtime.

, std::vector dynamic allocation.

1) ( )

2) , B, ( )

std::dynarray, :

, C++14, array TS C++17. , manlio.

, , . , , , . , .

+2
4

, , , . , , char[10] char[11] - . , , , ( sizeof). .

std::dynarray, . std::vector

+1

. -, : . . , , . -, , ++.

, std::vector. - , , , .

#include <vector>
#include <cstddef>

class A {
    private:
        class B {
            friend A;
            B(size_t n) : array(n) {}
            std::vector<int> array;
        };
    public:
        // Initialize b_member based on some computation.
        A(int i) : b_member(i + 2), b_ptr_member(new B(i + 3)) {}
        ~A() { delete b_ptr_member; }
    private:
        B b_member;
        B *b_ptr_member;
};

int main() {
    A a(10);
}
+1

++. . std::vector, std::vector::shrink_to_fit .:

class B {
  ...
  std::vector<int> a;
  ...
};
+1

: std::vector. :

1) ( )

. do , ( , , ).

/ , , <experimental/dynarray>... , IMHO, <vector>, : D

+1

Source: https://habr.com/ru/post/1541303/


All Articles