I’m trying intending to create a single instance of a type that gets shared among the items in a vector. Each of the vector’s item types requires a pass-by-reference parameter in the constructor but I can’t seem to get the vector to initialize properly.
//The type of each item in the vector
class PollingConfig_t
{
public:
PollingConfig_t(DebugPrinter_t& _debugPrinter) : _debugPrinter(debugPrinter) {}
private:
DebugPrinter_t& _debugPrinter; //Reference to the global instance of DebugPrinter_t
}
And for the actual globals:
DebugPrinter_t DebugPrinter(true); //One instance shared among vector items
std::vector<PollingConfig_t> PollingConfigs(4, PollingConfig_t(DebugPrinter)); //4 instances of PollingConfig_t, each with reference to DebugPrinter.
This doesn’t compile and give me an error:
error: use of deleted function 'PollingConfig_t& PollingConfig_t::operator=(const PollingConfig_t&)'
HOWEVER, I can get it work seemingly as intended if I simply remove the ampersand in the _debugPrinter declaration.
private:
DebugPrinter_t _debugPrinter;
But wouldn’t this create copies of the original instance DebugPrinter
for each of the vector’s items? I mean if _debugPrinter
is declared as a DebugPrinter_t
instead of DebugPrinter_t&
it’s no longer a reference, right?