Can I do this:
static Toggle GetAutoUpdatedToggle(DWORD key, bool initialState = false)
{
Toggle tempToggle(key, initialState);
autoUpdateToggles.push_back(tempToggle); //This is static member - std::vector<Toggle>
return tempToggle;
}
And I’m also using it later like that:
void Toggle::UpdateAllFromFactory() //This is static function
{
for each (Toggle toggle in autoUpdateToggles)
{
toggle.Update();
}
}
Is this good way of doing it?
UPDATE 1 – After your suggestoins:
static Toggle* GetAutoUpdatedToggle(DWORD key, bool initialState = false)
{
Toggle *pToggle = new Toggle(key, initialState);
m_autoUpdateToggles.push_back(pToggle);
return pToggle;
}
void Toggle::UpdateAllFromFactory()
{
for (std::vector<Toggle*>::iterator it = m_autoUpdateToggles.begin(); it < m_autoUpdateToggles.end(); it++)
{
(*it)->Update();
}
}
No, this is not a good way of doing it, because you pass around copies of
Toggle:GetAutoUpdatedTogglereturns a copy of theTogglethat it just pushed into thevector. It’s not in itself a wrong thing to do, but any manipulations the caller may do on the returned toggle would not be reflected on the one you pushed onto thevectorforloop goes through elements of thevector, creating a copy for use inside the loop body. Unless theToggleitself has a pointer-like semantic, theUpdate()action would not be reflected onToggleobjects inside thevector.To fix this issue, make
GetAutoUpdatedTogglereturn a reference to theToggleobject that it just pushed onto thevector, and use avector<Toggle>::iteratorobject to iterate through the stored toggles. This would let you operate on the actual objects, rather than on their copies.