c++ - 在函数中创建类实例并稍后使用它

标签 c++ oop class static

我可以这样做吗:

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;
}

我以后也会这样使用它:

void Toggle::UpdateAllFromFactory() //This is static function
{
    for each (Toggle toggle in autoUpdateToggles)
    {
        toggle.Update();
    }
}

这样做的好方法吗?


更新 1 - 在您提出建议后:

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();
    }
}

最佳答案

不,这不是一个好方法,因为你传递了 Toggle拷贝 :

  • GetAutoUpdatedToggle返回 Toggle拷贝它刚刚插入了vector .这本身并不是一件错误的事情,但是调用者可能对返回的切换进行的任何操作都不会反射(reflect)在您推到 vector 上的那个上。
  • for循环遍历 vector 的元素, 创建一个在循环体内使用的拷贝。除非Toggle本身具有类似指针的语义,Update()操作不会反射(reflect)在 Togglevector 中的对象.

要解决此问题,请制作 GetAutoUpdatedToggle返回对 Toggle引用它刚刚推到 vector 上的对象,并使用 vector<Toggle>::iterator对象遍历存储的切换。这将使您能够对实际对象进行操作,而不是对它们的拷贝进行操作。

关于c++ - 在函数中创建类实例并稍后使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13540854/

相关文章:

c++ - 简单类的GCC去虚拟化

c++ - 超市管理系统的类之间应该是什么关系?

c++ - 将大型成员对象移出类?

java - 哪个会使类文件变大?导入 java.awt.*,还是一堆或单个导入语句?

python - 派生类无法识别父类方法的参数

C++ 静态成员的多个实例

c++ - C++ 二进制文件如何替换自身?

c++ - 试图强制静态对象初始化

c++ - Qt静态库构建后不输出任何文件

c++ - 体系结构 x86_64 : using a structure defined in header file 的 undefined symbol