vendredi 27 mars 2015

Create object, add pointer to vector, then return it

I'm creating a menu class and currently manage controls like so:



// .h
class CTab
{
public:
...
CComboBox* AddCombo();

std::vector<CComboBox*> m_vecControls;
...
}

// .cpp
CComboBox* CTab::AddCombo()
{
auto *combo = new CComboBox();
m_vecControls.push_back(combo);
return combo;
}


I use a std::vector of pointers to easily iterate all controls when I'm rendering them. I also return the pointer to that object when I initialize the combobox so I can add items to it, for example:



auto *comboAge = AddCombo();
comboAge->AddItem("0-15");
comboAge->AddItem("16-30");
comboAge->AddItem("30+");


This all works fine, but I'm trying to implement the latest and greatest C++11 features, and I'm not sure which approach to take. Ownership of the controls belongs to the tab, and the ownership of the tab belongs to the window. Would it be best to stop using pointers altogether, and just create a



std::vector<CComboBox>

? Then I could use



m_vecControls.push_back(std::move(combo));

but I'm not sure what the best way to return a reference to that would be, so I could add items to it. Another option would be to use smart pointers, then I wouldn't have to delete the objects manually in CTab::~CTab(). So my questions are:




  1. Would it be best to stop using pointers, in favor of std::move? If so, how should I return a reference to the created object in AddCombo()?




  2. Or would it best to use smart pointers instead of raw pointers? If so, which type? I assume it would have to be shared because I'm keeping a vector of them, in addition to returning the pointer in AddCombo().




Aucun commentaire:

Enregistrer un commentaire