samedi 15 juillet 2017

Issues trying to construct `std::vector` with initializer list

Consider the following code:

#include <memory>
#include <vector>

class A {
public:
  explicit A(std::vector<int> &&v) : v_(std::move(v)) {}

private:
  std::vector<int> v_;
};

int main() {
  // compilation error (no matching call to std::make_unique)
  // compiler output: http://ift.tt/2tXz4FE
  std::vector<std::unique_ptr<A>> as1 = {std::make_unique<A>({1}),
                                         std::make_unique<A>({2})};

  // compilation error (requested copy of std::unique_ptr)
  // compiler output: http://ift.tt/2tfbeYP
  std::vector<std::unique_ptr<A>> as2 = {
      std::make_unique<A>(std::vector<int>({1})),
      std::make_unique<A>(std::vector<int>({2}))};

  // succeeds
  std::vector<std::unique_ptr<A>> as3;
  as3.push_back(std::make_unique<A>(std::vector<int>({1})));
  as3.push_back(std::make_unique<A>(std::vector<int>({2})));
}

  • For as1: I would expect std::make_unique<A>({1}) to call the implicit initializer list constructor of std::vector, then pass the vector to std::make_unique. Why doesn't this compile?
  • For as2: The result of std::make_unique is an rvalue. Why is a copy requested anywhere?
  • Is there a more idiomatic or shorter way to accomplish this than my as3?

Aucun commentaire:

Enregistrer un commentaire