jeudi 23 novembre 2017

Is this usage of shared_ptr correct?

I try to use shared_ptr to manage data of several types. So I use shared_ptr to hold different data type. The code below illustrates the idea:

struct MyClass
{
    int num;
    std::shared_ptr<void> ptr;
};

std::shared_ptr<void> f1(char c, int n)
{
    switch(c) //There are more cases. Here only for illustration. I 
              //want to return pointer of different data types.
    {
        case 'i':
        {
            return std::make_shared<int>(n);
            break;
        }
        case 's':
        {
            return std::make_shared<std::string>(to_string(n));
            break;
        }
        default:
        return NULL;
    }
}

vector<MyClass> f2()
{
    vector<MyClass> vec;
    char c;
    for(int i = 0; i < 10; i++)
    {
        c = 'i';//getchar();
        MyClass data;
        data.num = i;
        data.ptr = f1(c, i);
        vec.push_back(data);
    }
    return vec;

}

int main() {
    vector<MyClass> v;
    v = f2();
    for(auto e : v)
    {
        cout << e.num << " " << *(static_pointer_cast<std::string>(e.ptr)) << endl;
    }
    return 0;
}

Is my use of shared_ptr a good practice? Are there better ways?

Aucun commentaire:

Enregistrer un commentaire