版权声明:原创文章未经同意,禁止转载 https://blog.csdn.net/zmlovelx/article/details/82799559
需求:
多种继承类/子类 对象共同存放于容器中, 要求能push进不同对象,pop出来后能实现多态。
实现分析:
这种情况就得容器中存放基类指针,但是存放指针就意味着得自己管理内存,主动释放。 有没有方法让c++自己去管理呢,答案是用智能指针。
示例代码: 容器中存放的是unique_ptr, pop出来后可以转成shared_ptr给外界去调用。超级方便
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <memory>
#include <iostream>
using namespace std;
class Base
{
public:
Base();
~Base();
virtual void Func();
};
Base::Base()
{
printf( "%s\n", __func__ );
}
Base::~Base()
{
printf( "%s\n", __func__ );
}
void Base::Func()
{
printf( "base::%s\n", __func__ );
}
class Drived : public Base
{
public:
Drived();
~Drived();
virtual void Func();
};
Drived::Drived()
{
printf( "%s\n", __func__ );
}
Drived::~Drived()
{
printf( "%s\n", __func__ );
}
void Drived::Func()
{
printf( "drived:%s\n", __func__ );
}
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
std::list<std::unique_ptr<Base> > myList;
template<typename T>
void Push(const T &base)
{
myList.push_back(make_unique<T> (std::move(base)));
}
void Pop()
{
//std:unique_ptr<Base> ptr = std::move(myList.front());
std::shared_ptr<Base> ptr = std::move(myList.front());
ptr->Func();
myList.pop_front();
}
int
main( int argc, char **argv )
{
Drived drived;
Push(drived);
Pop();
return 0;
}
编译请加--std=c++11
输出:
./a.out
Base
Drived
drived:Func
~Base
~Drived
~Base
作者:帅得不敢出门 c++哈哈堂 31843264