#include<iostream>
#include<algorithm>
#include<vector>
#include<memory>
using namespace std;
class Widget
{
public:
Widget(int _id):id(_id){}
void SayHello()
{
cout<<"my id:"<<id<<endl;
}
~Widget(){};
private:
int id;
};
void CallSay(const auto_ptr<Widget>& wid_ptr)
{
auto_ptr<Widget> *p = (auto_ptr<Widget> *)(operator new(sizeof(auto_ptr<Widget>))); // 分配内存空间
new (p) auto_ptr<Widget>(wid_ptr);//auto_ptr<Widget>的构造函数要求参数是非const的,但wid_ptr是const的,从const转换为非const会产生编译错误。
}
int main()
{
auto_ptr<Widget> wid1(new Widget(1));
CallSay(wid1);
}auto_ptr预防作为STL容器元素的实现。
最新推荐文章于 2025-05-08 22:23:06 发布
本文通过一个具体的 C++ 代码示例介绍了如何使用 auto_ptr 类型,并展示了在构造函数调用过程中可能出现的编译错误。此外,还提供了一个 main 函数中的示例,用于创建并传递 auto_ptr 指针。
1759

被折叠的 条评论
为什么被折叠?



