Call another constructor conditionally

I want to call another constructor of the same class depending on the execution condition. The constructor uses different initialization lists (a bunch of things after :), so I can not handle the condition inside the constructor.

For instance:

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

I assume I can use a pointer.

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

Is there a better way if I haven't written a move constructor for my class?

+4
source share
2 answers

, , ( ), , initialize, , .

:

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

, - , , "dummy", . DoNothing :

 SomeClass object(DoNothing())
+2

-

std::vector<int> ptr_s;
if (condition) {
    ptr_s.resize(100);
} else {
    ptr_s.resize(10);
}

?

+1

Source: https://habr.com/ru/post/1671065/


All Articles