在 C++ 中,有没有办法在不发生移动或复制的情况下将值传递给构造函数?

In c++, is there a way to pass a value to a constructor without a move or copy happening?

我是第一次用 C++ 编写游戏引擎,我需要一个状态管理器/机器。我希望它拥有所有州的所有权。

当我开始深入研究函数通常如何工作时,我发现它们通常会将值复制或移动到函数中。这对我来说似乎没有必要。

我想要的是在别处临时创建值,将其传递给函数,并在状态机的内存中构建它,可以这么说,而不移动或复制该值。这可能吗?实用吗?

看起来像这样:

class StateManager {
  public:
    StateManager(State state) {
      this.state = state; // Magically have this.state be the passed state, without copying or moving the constructed state. I think it's called "In place construction"?
    }
  private:
    State state;
}

void main() {
  State state(12, 8); // Create an object with some parameters
  state.initialize(); // Maybe perform a few things on it
  StateManager states(state);
}

如果你想避免复制,你可以像这样通过const引用传递变量:

StateManager(const State& state);

const 表示状态的值不会改变, & 只是意味着我们正在传递一个内存地址。 (参考,非价值)

移动通常很便宜,因此并不需要不惜一切代价避免它。

您可以通过就地构建

提供接口来避免move/copy
class StateManager {
public:
    template <typename ... Ts>
    StateManager(in_place_t, Ts&&... args) : state(std::forward<Ts>(args)...){}

private:
    State state;
};

int main()
{
    StateManager states(std::in_place, 12, 8);
    // ...
}

注意:in_place_t 标记用作简单模板转发构造函数有可能拦截复制构造函数(非常量 StameManager&)的“问题”。 emplace.

方法不需要