有条件地调用其他构造函数

ham*_*els 6 c++ constructor

我想根据运行时条件调用同一类的不同构造函数。构造函数使用了不同的初始化列表(在之后的一堆东西:),因此我无法在构造函数内处理条件。

例如:

#include <vector>
int main() {
    bool condition = true;
    if (condition) {
        // The object in the actual code is not a std::vector.
        std::vector<int> s(100, 1);
    } else {
        std::vector<int> s(10);
    }
    // Error: s was not declared in this scope
    s[0] = 1;
}
Run Code Online (Sandbox Code Playgroud)

我想我可以使用指针。

#include <vector>
int main() {
    bool condition = true;
    std::vector<int>* ptr_s;
    if (condition) {
        // The object in the actual code is not a std::vector.
        ptr_s = new std::vector<int>(100, 1);
    } else {
        ptr_s = new std::vector<int>(10);
    }
    (*ptr_s)[0] = 1;
    delete ptr_s;
}
Run Code Online (Sandbox Code Playgroud)

如果我没有为类编写移动构造函数,还有更好的方法吗?

use*_*833 1

另一种解决方案是创建一个类,默认构造函数不会进行分配、计算(以及所有艰苦的工作),而是具有一个函数,例如initialize并为每个构造函数类型重载它以完成实际工作。

例如:

int main() {
    bool condition = true;
    SomeClass object;
    if (condition) {
        object.initialize(some params 1)
    } else {
        object.initialize(some params 2)
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可能希望默认构造函数做一些有意义的事情,在这种情况下,创建一个采用特定“虚拟”类型的对象的构造函数,例如,DoNothing并改为:

 SomeClass object(DoNothing())
Run Code Online (Sandbox Code Playgroud)