Reputation: 41
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
Upvotes: 1
Views: 65
Reputation: 172904
do all type declarations with
auto
generate an r-value ?
No. And it's irrelevant here.
d
is a std::shared_ptr<Derive>
, but foo
acceptes std::shared_ptr<Base>
, then it needs to be converted to std::shared_ptr<Base>
, which is a temporary object (an rvalue) and can't be bound to lvalue-reference to non-const, i.e. std::shared_ptr<Base>&
.
Upvotes: 2