c ++ container for storage management succession smart pointer class object

Copyright: original articles without consent, is prohibited reprint https://blog.csdn.net/zmlovelx/article/details/82799559

demand:

Multiple inheritance class / subclass object stored together in a container, the request can push into the different objects, pop out of the polymorphism can be achieved.

Achieve Analysis:

This situation must be stored in the container base class pointer, but the pointer storage means have their own memory management, active release. Is there a way to make yourself c ++ to manage it, the answer is to use smart pointers.

Sample Code: stored in the vessel is unique_ptr, the pop out to the outside can be converted into shared_ptr to call. Super easy

#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;
}

Compile Please add --std = c ++ 11

Output:

./a.out                  
Base
Drived
drived:Func
~Base
~Drived
~Base

Author: handsome too afraid to go out ha ha hall 31,843,264 c ++

Guess you like

Origin blog.csdn.net/zmlovelx/article/details/82799559