如何有条件地实例化一个对象?

How can I conditionally instantiate an object?

我正在尝试像这样做一些有条件的工作:

Type object;
if (cond) {
    doSomeStuff();
    object = getObject();
    doMoreStuff();
} else {
    doSomeOtherStuff();
    object = getDifferentObject();
    doEvenMoreStuff();
}
use(object);

我能想到的解决这个问题的唯一方法是复制 use 代码(实际上是我应用程序中的内联代码)并在 [=14= 的每个分支中声明 object ] 堵塞。如果我想避免重复代码,我必须将它包装在一些使用函数中,就像我在上面所做的那样。在实际情况下,这个 use 函数可能会使用 5 个以上的参数来基本上传递上下文。这一切看起来很乱,而且无法维护。

if (cond) {
    doSomeStuff();
    Type object = getObject();
    doMoreStuff();
    use(object);
} else {
    doSomeOtherStuff();
    Type object = getDifferentObject();
    doEvenMoreStuff();
    use(object);
}

解决此问题的最佳方法是什么? Type 没有默认构造函数,因此片段 1 无法编译。

一些其他语言支持片段 1 - 相关问题:Forcing uninitialised declaration of member with a default constructor

您可以使用 IIILE(立即调用初始化 lambda 表达式):

auto object = [&] {
  if (cond) {
    doSomeStuff();
    auto object = getObject();
    doMoreStuff();
    return object;
  } else {
    doSomeOtherStuff();
    auto object = getDifferentObject();
    doEvenMoreStuff();
    return object;
  }
}();  // note that the lambda must be called

use(object);

即使 Type 不是默认构造的,这也会起作用。

这是一个demo

将其放入一个函数中:

Type doStuffAndCreateType() {
    doSomeStuff();
    Type object = getObject();
    doMoreStuff();
    return object;
}

Type doOtherStuffAndCreateType() {
    doSomeOtherStuff();
    Type object = getObject();
    doEvenMoreStuff();
    return object;
}

Type object = cond ? doStuffAndCreateType() : doOtherStuffAndCreateType();
use( object );

看看std::optional:

#include <optional>

std::optional<Type> object;
if (cond) {
    doSomeStuff();
    object = getObject();
    doMoreStuff();
} else {
    doSomeOtherStuff();
    object = getDifferentObject();
    doEvenMoreStuff();
}
use(object.value());