lock weak_ptr to const shared_ptr reference

Got a little confusion here on how auto works.

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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#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
	
	const auto & 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;
}
Binding a temporary object to a const reference extends the life time of the temporary object.
Topic archived. No new replies allowed.