std :: auto_ptr的最佳实践

vls*_*vls 3 c++ smart-pointers

我只是习惯了使用std :: auto_ptr的智能指针.

假设我想用auto_ptr和普通指针调用一个函数.

auto_ptr<uint32> data_smart(new uint32[123])]);
uint32 data_fix[123];
uint32* data_dumb = new uint32[123];

processData(data_smart);
processData(data_fix);
processData(data_dumb);
Run Code Online (Sandbox Code Playgroud)

没有超载的最佳做法是什么?使用带有uint32*参数的processData函数?我可以使用.get()将智能指针强制转换为uint32*吗?或者我应该怎么做?提前致谢!

ybu*_*ill 5

1.

auto_ptr<uint32> data_smart(new uint32[123])]);
Run Code Online (Sandbox Code Playgroud)

不要那样做.auto_ptr仅适用于标量(它调用delete而不是delete[]).

2. auto_ptr拥有它指向的对象,因此除非你想将所有权传递给该函数(在你的代码中你没有),该函数应该接受一个普通的指针.所以你应该把呼叫改为:

processData(data_smart.get());
Run Code Online (Sandbox Code Playgroud)

为了明确表达data_smart继续拥有该对象.