lundi 24 décembre 2018

Does vector

I used a reference_wrapper recently like so:

#include <iostream>
#include <vector>
#include <functional>
#include <memory>

struct A {
};

struct B {
    B() {};
    B(A& aA) {};
    B(const B&) = default;
};

int main () {
    A a;
    B b;

    std::vector<std::reference_wrapper<B>> rvector;
    rvector.push_back(std::reference_wrapper<B>(b)); // (1)
    rvector.push_back(b); // (2)

1 and 2, are both compiling and working just fine and I wonder which is the right one! So I thought that the following could work too:

    std::vector<B> bvector;
    bvector.push_back(a); // (3)
    bvector.push_back(b); // (4)
    std::cout << bvector.size() << "\n";

yeap, it works! So I came to the conclusion that push_back just calls the type's T constructor with the given parameter. Documentation though mentions that the parameter is of type T and eventually the copy/move ctor since the parameter is of type T.

When I tried 1 and 2 with shared_ptr though:

    std::vector<std::shared_ptr<B>> pvector;
    pvector.push_back(std::shared_ptr<B>(new B())); // (5)
    pvector.push_back(new B()); // (6)

I get

no matching function for call to 'std::vector<std::shared_ptr<B> >::push_back(B*)'

  • Why 2 and even 3 work but 6 doesn't?
  • There should be a shared_ptr<B>constructor that takes B* as parameter, isn't there? So, why 6 does not compile (since 3 does)?
  • Since 3 compiles and works just fine, would it be ok to use and count on it (if it wasn't a bad approach since there is the emplace_back)?

Aucun commentaire:

Enregistrer un commentaire