I’m trying to learn about pointers and references.
//define some int variables
int a = 1;
int b = 2;
// define a list of integers
std::list<int> myInts{ a, b };
// define references to those integers
int& aRef = a;
int& bRef = b;
// define a list of references
std::list<int&> myIntReferences{ aRef, bRef };
// define pointers to the integer variables
int* aPointer = &a;
int* bPointer = &b;
// define a list of integer pointers
std::list<int*> myIntPointers{ aPointer, bPointer };
So far so good, so I attempt to do the same with, for example, some DrumButton objects…
// define the buttons
DrumButton bassDrumButton{ "Bass Drum", "36" };
DrumButton snareDrumButton{ "Snare Drum", "38" };
DrumButton openHatButton{ "Open Hat", "42" };
DrumButton closedHatButton{ "Closed Hat", "46" };
/// put them in a list - doesnt work!!
std::list<DrumButton> myButtonsList({ bassDrumButton, snareDrumButton });
/// try to add them with 'address of' - does work!! eh what??
std::list<DrumButton> myButtonsList{ &bassDrumButton, &snareDrumButton };
/// ..but adding one more and it fails - 'cannot initialize with with initializer list!?!?
std::list<DrumButton> myButtonsList{ &bassDrumButton, &snareDrumButton, &openHadButton };
/// try with pointers and no such problem
std::list<DrumButton*> buttons = { &bassDrumButton, &snareDrumButton, &openHatButton, &closedHatButton };
So that’s confusing - why on earth could I not add the buttons as ordinary variables - and why is there no error when I add two using the ‘address of’ but adding more is not allowed?
I then tried to explicitly define some DrumButton references and put those in a list of DrumButton references…
DrumButton& bdRef = bassDrumButton;
DrumButton& sdRef = snareDrumButton;
DrumButton& ohRef = openHatButton;
DrumButton& chRef = closedHatButton;
/// didn't work
std::list<DrumButton&> myButtons{ bdRef, sdRef, ohRef, chRef };
/// but I could add them one by one like this..
myButtons.emplace_back(bd);
myButtons.emplace_back(sd);
Finally, I have been advised to avoid raw pointers as much as possible so I tried to make a list of unique_pointers…
/// first define a couple of DrumButton pointers..
std::unique_ptr<DrumButton> buttonPointer = std::make_unique<DrumButton>();
std::unique_ptr<DrumButton> anotherButtonPointer = std::make_unique<DrumButton>();
/// Then define a list of DrumButton pointers..
std::list<std::unique_ptr<DrumButton>> listOfButtonPointers;
// add to the list..
listOfButtonPointers.push_back(buttonPointer);
listOfButtonPointers.push_back(anotherButtonPointer);
This seemed to work - but can it be done in a more compact way like list initialization?