完美转发c++

Max*_*Max 0 c++

这是正确的使用方法吗std::forward?

struct Command {
public:
  int32_t uniqueID{0};

public:
  Command() = default;
  
  template<typename T>
  Command(T&& _uniqueID) : uniqueID(std::forward<int32_t>(_uniqueID)) //
  {
    //
  }
};
Run Code Online (Sandbox Code Playgroud)

或者我应该使用这条线?

Command(T&& _uniqueID) : uniqueID(std::forward<T>(_uniqueID))
Run Code Online (Sandbox Code Playgroud)

eer*_*ika 5

这是使用 std::forward 的正确方法吗?

不,这里没有任何用处std::forward。移动基本类型与复制它相同。我建议如下:

Command(std::int32_t _uniqueID) : uniqueID(_uniqueID) {}
Run Code Online (Sandbox Code Playgroud)

或者,让类成为一个聚合:

struct Command {
    std::int32_t uniqueID{0};
};
Run Code Online (Sandbox Code Playgroud)

  • 你怎么知道在 OP 的例子中 `T` 是一个原始类型? (3认同)
  • @DanielLangr,其行为与我建议的解决方案相同:https://godbolt.org/z/qMWKaq88x (2认同)