gpt4 book ai didi

c++ - 关于 auto_ptr::reset 的问题

转载 作者:行者123 更新时间:2023-11-30 00:41:39 24 4
gpt4 key购买 nike

谁能解释一下this code from C++ Reference site :

#include <iostream>
#include <memory>
using namespace std;

int main () {
auto_ptr<int> p;

p.reset (new int);
*p=5;
cout << *p << endl;

p.reset (new int);
*p=10;
cout << *p << endl;

return 0;
}

最佳答案

auto_ptr 管理一个指针。 reset 将删除它拥有的指针,并指向其他内容。

所以你从 auto_ptr p 开始,没有指向任何东西。当您使用 new int reset 时,它不会删除任何内容,然后指向动态分配的 int。然后,您将 5 分配给该 int

然后您再次重置,删除之前分配的int,然后指向新分配的int。然后,您将 10 分配给新的 int

当函数返回时,auto_ptr 超出范围并调用其析构函数,删除最后分配的 int,程序结束。

关于c++ - 关于 auto_ptr::reset 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3272810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com