Determine array size in constructor initializer

前端 未结 12 2411
失恋的感觉
失恋的感觉 2020-12-08 21:10

In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?

class Class
{
public:
  int         


        
12条回答
  •  青春惊慌失措
    2020-12-08 21:52

    Like already suggested, vector is a good choice for most cases.

    Alternatively, if dynamic memory allocation is to be avoided and the maximum size is known at compile time, a custom allocator can be used together with std::vector or a library like the embedded template library can be used.

    See here: https://www.etlcpp.com/home.html

    Example class:

    
    #include 
    
    class TestDummyClass {
    public:
        TestDummyClass(size_t vectorSize) {
            if(vectorSize < MAX_SIZE) {
                testVector.resize(vectorSize);
            }
        }
    
    private:
        static constexpr uint8_t MAX_SIZE = 20;
        etl::vector testVector;
        uint8_t dummyMember = 0;
    };
    

提交回复
热议问题