Initialize the size of std :: array in the constructor of the class that uses it

Is it possible to use std::array<class T, std::size_t N> as a private attribute of a class, but initialize its size in the class constructor ?

 class Router{ std::array<Port,???> ports; //I dont know how much ports do will this have public: Switch(int numberOfPortsOnRouter){ ports=std::array<Port,numberOfPortsOnRouter> ports; //now I know it has "numberOfPortsOnRouter" ports, but howto tell the "ports" variable? } } 

I could use a pointer, but can this be done without it?

+4
source share
4 answers

No, the size must be known at compile time. Use std::vector instead.

 class Router{ std::vector<Port> ports; public: Switch(int numberOfPortsOnRouter) : ports(numberOfPortsOnRouter) { } }; 
+4
source

You must make your Router class a class class.

 template<std::size_t N> class Router{ std::array<Port,N> ports; ... } 

if you want to specify the size of ports at the Router level . By the way, N must be a constant known from compilation time.

Otherwise, you will need std::vector .

+5
source

The size of std::array<T, N> is a compile-time constant that cannot be changed at runtime. If you need an array with flexible borders, you can use std::vector<T> . If the size of your array does not change, and you somehow know the size from its context, you can use std::unique_ptr<T[]> . It is a bit lighter, but also does not help when copying or resizing.

+3
source

std::array - an array of fixed lengths . Therefore, the length must be known at compile time. If you need an array with dynamic length, you want to use std::vector instead:

 class Router{ std::vector<Port> ports; public: Switch(int numberOfPortsOnRouter):ports(numberOfPortsOnRouter){} }; 
+2
source

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


All Articles