简体   繁体   中英

c++ microcontroller global classes/singelton?

I am currently using C++ on a microcontroller and I am having an issue where I don't know what the proper implementation is:

I am for example using an serial interface class which takes care of configuring the serial port (setting baud, data bits...). Since I only want to do it at the initialization phase of my MCU at the start, I don't know how to handles this with classes.

Shall I make a global class/singleton which I create at the initialization phase (in this way I can keep my serial parameters) or shall i create a class everytime I need to use the serial interface (but this would reopen my serial line - or do I leave the constructor empty)?

Thanks a lot in advance.

I try to avoid global variables and singletons.

I defined a class with a constructor that accepts a pathname and configuration to open the port, and a destructor that closes the port. Then, I declared a static local instance of it in main(...) and I passed references to it in to the constructors of other classes that needed to use the port.

Passing the reference around (as opposed to declaring a global instance, or a global function to get a singleton) is what enabled me to write unit tests for the other classes in which the tests passed in a references to mock serial port objects.

You are asking for opinions because all options are valid.
I do believe creating a singleton to store the configuration and resources needed is a good approach. This way you can implement RAII idiom, and gain easy access when needed.

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