简体   繁体   中英

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

I'm writing a game engine in C++ for the first time and I need a state manager / machine. I want it to have ownership of all states.

When I started digging into how functions usually work, I found out they normally copy or move a value into the function. That seems unnecessary to me.

What I want is to create the value temporarily elsewhere, pass it to the function, and have it be constructed in the state machine's memory, so to speak, without moving or copying that value. Is this possible? And is it practical?

It would look like this:

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

Move is generally cheap, so avoiding it at all cost is not really needed.

You can provide interface to avoid move/copy by constructing in-place

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);
    // ...
}

Note: in_place_t tag is used as simple template forwarding constructor has "issue" which might intercept copy constructor (non-const StameManager& ). not needed for method as emplace .

If you want to avoid copying, you can just pass the variable in by const reference like this:

StateManager(const State& state);

The const indicates that the value of state will not change and & just means we're passing in a memory address. (By reference, not value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM