On C++ primer 5 edition. chapter 12 Dynamic Memory:
Consider the following function that operates on a shared_ptr:
// ptr is created and initialized when process is called void process(shared_ptr<int> ptr) { // use ptr } // ptr goes out of scope and is destroyed
The parameter to process is passed by value, so the argument to process is copied into ptr. Copying a shared_ptr increments its reference count. Thus, inside process the count is at least 2. When process completes, the reference count of ptr is decremented but cannot go to zero. Therefore, when the local variable ptr is destroyed, the memory to which ptr points will not be deleted. The right way to use this function is to pass it a shared_ptr:
shared_ptr<int> p(new int(42)); // reference count is 1 process(p); // copying p increments its count; in process the reference count is 2 int i = *p; // ok: reference count is 1
It is said that use_count in process
is at least 2 thus when ptr
goes out of scope it is destructed but the memory of object it manages is not freed?!
I think it is logically but consider this:
void process(shared_ptr<int> sp) {
cout << sp.use_count() << endl;
cout << *sp << endl;
}
int main(){
process(shared_ptr<int>(new int(57)));
}
The output:
1 and it is not 2 as he said?
57
- Does this mean some
std::move
was applied by the compiler as an optimization? - Does he mean a memory-leak will happen in his example if no optimization was applied by the compiler to remove the Copy?