Best way to write constructor of a class who holds a STL container in C++11

前端 未结 3 1527
[愿得一人]
[愿得一人] 2020-12-31 14:54
class Foo {
  std::vector data_;
};

Say Foo can only be constructed by make a copy (technically I mean a copy or move)

3条回答
  •  旧巷少年郎
    2020-12-31 15:30

    The complexity problem of the performance optimal solution mentioned in Howard Hinnant's answer for constructors taking multiple arguments would be solved by use of perfect forwarding:

    template
    Foo(A0 && a0) : data_(std::forward(a0)) {}
    

    In case of more parameters, extend accordingly:

    template
    Foo(A0 && a0, A1 && a1, ...)
     : m0(std::forward(a0))
     , m1(std::forward(a1))
     , ...
     {}
    

提交回复
热议问题