void *元素的向量创建和删除

时间:2019-06-14 17:50:39

标签: c++ pointers vector

我想创建一个可以同时存储int和double值的向量。只是为了学习,我知道我可以使用boost :: hold_any或struct {int a,double b}。

我的问题是,在创建元素后,就立即将其删除。那可能是因为其他元素的寿命。但是我该如何处理呢?我想在向量中保留并保留四个“ any”。

代码:

#include <iostream>
#include <vector>
using namespace std;

const int NUM_OF_ELEMENTS = 4;

struct any {
    size_t type = -1;
    void* data;

    any(int value) {
        cout << "creating data " << value << " of type " << 0 << endl;
        type = 0;
        data = new int(value);
    }

    any(double value) {
        cout << "creating data " << value << " of type " << 1 << endl;
        type = 1;
        data = new double(value);
    }

    ~any() {
        cout << "deleting data of type " << type << endl;
        if (type == 0) {
            //delete (int*)data;
        } else if (type == 1) {
            //delete (double*)data;
        }
    }
};

void test() {
    vector<any> v;
    v.reserve(NUM_OF_ELEMENTS);

    for (int i = 0; i < NUM_OF_ELEMENTS; i++) {
        v.push_back(any(i));
    }

    for (int i = 0; i < NUM_OF_ELEMENTS; i++) {
        if (v[i].type == 0) {
            cout << "value: " << *(int*)v[i].data << endl;
        } else {
            cout << "value: " << *(double*)v[i].data << endl;
        }
    }
}


int main() {
    test();
    return 0;
}

输出:

creating data 0 of type 0
deleting data of type 0
creating data 1 of type 0
deleting data of type 0
creating data 2 of type 0
deleting data of type 0
creating data 3 of type 0
deleting data of type 0
value: 0
value: 1
value: 2
value: 3
deleting data of type 0
deleting data of type 0
deleting data of type 0
deleting data of type 0

另一件事是在第二个循环中进行访问,在该循环中我打印了值。这是最有效/最快的方法吗?

谢谢。

编辑:我看不到这是链接问题的重复之处。它一点也没有帮助我。为什么我的“ any”被解构两次?为什么值仍然存在?这是省钱还是幸运?由于我使用的是new,因此我应该自己删除这些值,但是如果取消注释解构函数中的行,程序将崩溃。

0 个答案:

没有答案