C ++入门5版:将临时shared_ptr传递给函数[duplicate]

问题描述 投票:1回答:1

此问题已经在这里有了答案:

关于C ++入门5版。第十二章动态内存:

考虑以下在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

要处理的参数按值传递,因此要处理的参数被复制到ptr中。复制shared_ptr会增加其引用计数。因此,在进程内部,该计数至少为2。当进程完成时,ptr的参考计数将递减,但不能为零。因此,当局部变量ptr为销毁后,不会删除ptr指向的内存。使用此函数的正确方法是将其传递给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

据说process中的use_count至少为2,因此,当ptr超出范围时,它会被破坏,但是它管理的对象的内存不会被释放?

我认为这在逻辑上是合理的,但请考虑一下:]

void process(shared_ptr<int> sp) {
    cout << sp.use_count() << endl;
    cout << *sp << endl;    
}

int main(){
    process(shared_ptr<int>(new int(57)));
}

输出:

1,不是他所说的2?

57

  • 这是否意味着编译器应用了某些std::move作为优化?
  • 他的意思是,如果编译器未应用任何优化来删除复制,那么在他的示例中将发生内存泄漏?
  • 关于C ++入门5版。第12章动态内存:考虑以下在shared_ptr上运行的函数://当进程被称为void时,将创建并初始化ptr void process(shared_ptr&...

    c++ shared-ptr move-semantics pass-by-value copy-elision
    1个回答
    0
    投票

    之所以在函数内部具有1的引用计数,是因为您向该函数传递了一个临时变量:

    process(shared_ptr<int>(new int(57)));
    
    © www.soinside.com 2019 - 2024. All rights reserved.