vendredi 31 mars 2017

C++ | For what exactly are boost.bind and boost.shared_ptr useful?

Yesterday i used boost libraries for the first time. I was told by a teacher to learn Observer design pattern. Then somewhere i read that in C++ you use Boost::Signals2 for the implementation of the pattern.

Then learning to use Boost::Signals2 i had to learn what is and how to use Boost::bind. But in order to use it i had to use and learn Boost::shared_ptr...

This is my code:

#include <iostream>
#include <boost/signals2.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost;
using namespace std;

class Animal {
    public:
        virtual ~Animal(){};

        virtual void talk(){};
    protected:
        string name;
};



class Mammal : public Animal {
    public:
        Mammal(string NAME);
        ~Mammal(){};

        void talk();
};

class Oviparous : public Animal {
    public:
        Oviparous(string NAME);
        ~Oviparous(){};

        void talk();
};

Mammal::Mammal(string NAME){ name = name;};
Oviparous::Oviparous(string NAME){ name = name;};
void Mammal::talk(){ cout<<"Meeeeeawww de: "<<name<<endl;};
void Oviparous::talk(){ cout<<"Wwwweeeeegh de: "<<name<<endl;};

int main(int argc, char * argv[]){

    signals2::signal<void ()> sig;

    Oviparous * animal2 = new Oviparous("Serpiente");
    Mammal * animal = new Mammal("Perro");
    shared_ptr<Mammal> animal3(new Mammal("Vaca"));


    sig.connect(bind(&Mammal::talk,animal));
    sig.connect(bind(&Oviparous::talk,animal2));
    sig.connect(bind(&Mammal::talk,animal3));
    sig();
    return 0;
};

The output is:

Meeeeeawww de: Perro
Wwwweeeeegh de: Serpiente 
Meeeeeawww de: Vaca

This code was a test to see if i can use boost.signals without using boost.shared_ptr, and i was able to. I would like if someone can explain me why is shared_ptr better than a normal pointer. Also, i dont totally understand boost.bind... if i had to explain what it does, i would say that it associates a class method with an instanced object ( i know this is really vague, and boost.bind can do a lot more than that, but i simply dont understand that much of it).

TL;DR: why is shared_ptr better than a normal pointer? what does boost.bind do?

Aucun commentaire:

Enregistrer un commentaire