我试图体验smart_ptrs,所以我试图从函数中返回unique_ptr:
unique_ptr<int> foo()
{
int x = 100;
unique_ptr<int> up(new int);
cout << "value stored in up : " << *up << endl;
cout << "get : " << up.get() << endl;
up.reset(&x);
cout << "value stored in up : " << *up << endl;
cout << "get : " << up.get() << endl;
return up;
}
int main()
{
auto up = foo();
cout << "value stored in up : " << *up << endl;
cout << "get : " << up.get() << endl;
return 0;
}
正如我所预期的那样,指向foo最后指向的同一个地址,就在main up中的print语句保持100之前,正如我所预料的那样,问题是在我打印存储的值之前在up,它被重置,所以我打印其他东西,然后调试断言失败,我对它发生的原因一无所知..