简体   繁体   中英

How to Initialize array of pointers in a c++ Initializer List

My class has an array of pointers ( Code edited for illustrating point )

class IMX6S::IMX6SAnalogIn : public AP_HAL::AnalogIn {
public:
    IMX6SAnalogIn();

private:
    IMX6S::IMX6SAnalogSource* _channels[2];
};

class IMX6S::IMX6SAnalogSource : public AP_HAL::AnalogSource {
public:
    friend class IMX6S::IMX6SAnalogIn;
    IMX6SAnalogSource(int16_t pin, float initial_value);


};

I want to initialize the _channels array in the initializer list of the constructor so I attempt the following

IMX6SAnalogIn::IMX6SAnalogIn() :
     _channels{&IMX6SAnalogSource(0,0.0f),&IMX6SAnalogSource(1,0.0f) }
{
}

However I get a warning - Taking address of temporary. in the initializer list

Is this way of initializing the array in the initializer list incorrect?

Note - I cannot dynamically allocate memory. Everything has to be statically allocated.

You can stop making it an array of pointers and make it an array of objects:

std::array<IMX6S::IMX6SAnalogSource, 2> _channels;

IMX6SAnalogIn::IMX6SAnalogIn() :
     _channels{{0,0.0f},{1,0.0f}}
{
}

There is no way to do this with an array of pointers without allocating memory. Well, you could make the objects direct members of the class and store pointers to them in an array that's also a member of the class. But that's functionally no different than the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM