其他分享
首页 > 其他分享> > 函数中的C auto_ptr(作为参数和返回值)

函数中的C auto_ptr(作为参数和返回值)

作者:互联网

我试图在我的代码中使用auto_ptr,但显然出了问题.

auto_ptr<ClassType> Class(s.Build(aFilename)); //Instantiation of the Class object
int vM = s.GetM(Class);
int vS = s.Draw(Class);

奇怪的是,在实例化Class之后,Class对象就存在了
通过调用s.GetModelMean(Class),Class不为空.但退出GetM功能后,
类是空的,因此不再可用.调用Draw函数时发生崩溃.

我按以下方式声明了这些函数:

int GetM(auto_ptr<ClassType> aM); 

似乎班级被摧毁了,但我不明白为什么……

解决方法:

你不要给auto_ptr作为函数的参数.要么:

int GetM(const auto_ptr<ClassType>&)

要么

int GetM(ClassType&)

要么

int GetM(ClassType*)

(也可能与const – 取决于你正在做什么).第一个你会用同样的方式调用,第二个函数你会这样调用:

int vM = s.GetM(*Class.get())

没有明星的最后一个.

原因是:GetM将复制auto_ptr(而不是Class对象)并在返回时销毁auto_ptr. auto_ptr(它是作用域指针或唯一指针 – 不是引用计数器!)将破坏Class.

无论如何:auto_ptr非常破碎.只要有可能(您的编译器已经支持C 11的一些小部分),请使用std :: unique_ptr和std :: shared_ptr(最后一个引用计数). unique_ptr不允许你像那样乱用它(因为不允许复制它 – 这更有意义).

标签:auto-ptr,c
来源: https://codeday.me/bug/20190823/1696264.html