gpt4 book ai didi

c++ - 关于 auto_ptr 的问题

转载 作者:太空狗 更新时间:2023-10-29 20:29:25 26 4
gpt4 key购买 nike

假设,我们有以下代码

auto_ptr<T> source() 
{
return auto_ptr<T>( new T(1) );
}
void sink( auto_ptr<T> pt ) { }
void f()
{
auto_ptr<T> a( source() );
sink( source() );
sink( auto_ptr<T>( new T(1) ) );
vector< auto_ptr<T> > v;
v.push_back( auto_ptr<T>( new T(3) ) );
v.push_back( auto_ptr<T>( new T(4) ) );
v.push_back( auto_ptr<T>( new T(1) ) );
v.push_back( a );
v.push_back( auto_ptr<T>( new T(2) ) );
sort( v.begin(), v.end() );
cout << a->Value();
}
class C
{
public: /*...*/
protected: /*...*/
private: /*...*/
auto_ptr<CImpl> pimpl_;

我很感兴趣:什么是好的,什么是安全的,什么是合法的,什么不是这个代码?据我所知,auto_ptr 是这样的,例如下面的代码

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

int main(int argc, char **argv)
{
int *i = new int;
auto_ptr<int> x(i);
auto_ptr<int> y;

y = x;

cout << x.get() << endl; // Print NULL
cout << y.get() << endl; // Print non-NULL address i

return 0;
}

此代码将为第一个 auto_ptr 对象打印 NULL 地址,为第二个对象打印一些非 NULL 地址,表明源对象在赋值过程中丢失了引用 (=)。不应删除示例中的原始指针 i,因为它会被拥有该引用的 auto_ptr 删除。事实上,new int 可以直接传递给 x,而不需要 i。我如何确定我的代码中哪一行是安全的,哪一行不安全?

最佳答案

vector<auto_ptr<T>> v;
v.push_back(auto_ptr<T>( new T(3) ));
v.push_back(auto_ptr<T>( new T(4) ));
v.push_back(auto_ptr<T>( new T(1) ));

标准完全禁止这样做。

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

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