C ++ Generic Data Type

I have a generic data type that is passed by value but does not support type information. We only store pointers and basic data types (e.g. int, float, etc.). Now for the first time we need to save std :: string inside this. Therefore, we decided to convert it to std :: string * and save it. Then the problem of destruction arises. We do not like to copy std :: string every time. Therefore, I am thinking of such an approach. Let's say the data type is as follows:

class Atom
{
public :
     enum flags
     {
         IS_STRING,
         IS_EMPTY,
         HAS_GOT_COPIED,

         MARKER
     };

private:
     void*   m_value;
     std::bitset<MARKER>   m_flags;

public:
    .....
    Atom( Atom& atm )
    {
        atm.m_flags.set( HAS_GOT_COPIED );
        ..... 
    }
    .....
    ~Atom()
    {
        if( m_flags.test(IS_STRING) && !m_flags.test(HAS_GOT_COPIED) )
        {
             std::string*  val = static_cast<std::string*>(m_value);
             delete val;
        }
    }
};

Is this a good approach to find out if there is a link to std :: string *? Any comments ..

I looked boost :: any and poco :: DynamicAny. Since I need serialization, I cannot use them.

Thanks, Gokul.

+3
source share
5

, , " ". , . , , Atom :

Atom a("hello world");

if (...) {
    Atom b(a);
    // b is destroyed, deleting the string
}

// Uh oh, the string been deleted but a is still referencing it.
cout << (string) a;

. boost::any , m_value Atom. //.

+4

, boost:: shared_ptr ( std:: tr1:: shared_ptr).

+4

, "copy on write" google . , .

boost::any?

+3

-. ( ) , comp.lang.++. .

, JsonCpp. , , : , , bool, int, array, object .. (Json:: .

+2

Besides, is this type of “universal data type” a good idea if you don't copy the string, can this class be sure that it owns the string that the pointer is on? Can you guarantee that only the lines highlighted through newwill be passed to the class in order to obtain ownership?

The design of this class looks as if it would be problematic.

+1
source

Source: https://habr.com/ru/post/1739359/


All Articles