samedi 13 mars 2021

Passing an 'auto' declared std::shared_ptr

Compiling with g++ -std=c++11 -pedantic-errors -Wall -Wextra -g

void foo(std::shared_ptr<Base>& ptr) {
    std::cout << "foo()\n";
    std::cout << "count = " << ptr.use_count() << "\n";     
}

int main(int argc, char* argv[]) {
    auto d = std::make_shared<Derived>(5);
    foo(d);

    return 0;
}

I get the following error:

shared_ptr.cpp:47:10: error: cannot bind non-const lvalue reference of type ‘std::shared_ptr<Base>&’ to an rvalue of type ‘std::shared_ptr<Base>’
     foo(d);

If I change the declaration of d to std::shared_ptr<Base> d the code compiles.

My question is: do all type declarations with auto generate an r-value ?

Any reading material about this matter is much appreciated, Thanks

Aucun commentaire:

Enregistrer un commentaire