vendredi 12 novembre 2021

Detecting null pointers inside vector of boos::variant

Following the question in Heterogenous vectors of pointers. How to call functions.

I would like to know how to identify null points inside the vector of boost::variant.

Example code:

#include <boost/variant.hpp>
#include <vector>

template< typename T>
class A
{
    public:
        A(){}
        ~A(){}

        void write();

    private:
        T data;
};

template< typename T>
void A<T>::write()
{
    std::cout << data << std::endl;
}

class myVisitor
: public boost::static_visitor<>
{
    public:
        template< typename T>
        void operator() (A<T>* a) const
        {
            a->write();
        }
};

int main()
{
   A<int> one;
   A<double> two;

   typedef boost::variant<A<int>*, A<double>* > registry;
   std::vector<registry> v;

   v.push_back(&one);
   v.push_back(&two);

   A<int>* tst = new A<int>;

   for(auto x: v)
   {
       boost::apply_visitor(myVisitor(), x);
       try {delete tst; tst = nullptr;}
       catch (...){}
   }

}

Since I am deleting the pointer I would hope that the last one will give me an error or something. How can I check if the entry in the entry is pointing to nullptr?

Aucun commentaire:

Enregistrer un commentaire