I've got this test program blow. I'm taking the reference to the return value of weak_ptr.lock(), which I presume is a bad idea. But it works, and it increments the use_count of the shared_ptr. Why? If I instead type out the full typename instead of using auto and try to assign it to a reference, it doesn't increment the use_cound (as expected).
#include <cstdio>
#include <memory>
class Foo {
public:
~Foo(){ printf("destroy\n");fflush(stdout); }
};
int main ( void ) {
std::shared_ptr<Foo> bar(std::make_shared<Foo>());
printf("bars ref: %d\n", bar.use_count()); // prints 1
std::weak_ptr<Foo> barw(bar);
const std::weak_ptr<Foo>& bad = barw.lock(); // taking reference to temporary.
printf("bars ref: %d\n", bar.use_count()); // prints 1 as expected
constauto & bars = barw.lock(); // taking reference to temporary
printf("bars ref: %d\n", bar.use_count()); // prints 2. Why? Shouldn't the temporary be destroyed and set the count back to 1?
return 0;
}