malloc allocates some space, but does not put anything into it. It works great for structures with flat old data (or trivially initialized classes), and in C everything you have.
In C ++, you have classes, such as std::vector among others, that must be built correctly in order to set some invariants. This is done using a direct declaration for objects with automatic storage duration, but for objects with dynamic allocation, you need to use new instead of malloc .
For instance,
std::vector<int> global; // (1) void foo() { std::vector<int> local; // (2) std::vector<int> *bad = malloc(sizeof(*bad)); // (3) std::vector<int> *good = new std::vector<int>; // (4) std::unique_ptr<std::vector<int>> better(new std::vector<int>); (5) }
- excellent - this global is initialized (by which I mean that the constructor is called) automatically
- excellent - this local variable is also automatically created and destroyed properly as soon as
foo exits - you cannot use
bad for anything because any method you call assumes the constructor is already running and it is not- ok, you cannot use
bad for anything without explicitly building it using the new placement. You should not do this, but this is only appropriate when you are doing smart or complex things with custom allocation.
- This is normal (but note that you must remove it manually -
foo has a memory leak) - it's better - you do not need to clean it manually
Now notice that your node class also has a constructor. In this case, it is automatically generated and does nothing but call the vector constructor. However, you need it to be called, which means using new to dynamically highlight the node .
So your program should probably be more like:
std::vector<std::unique_ptr<node>> data; ... std::unique_pre<node> temp(new node); temp->addPoints(...); data[index]->addChild(temp);
Note. I assume that data[index] is valid (I see that from addChild you know how to fill the vector already), and that the single-owner model implemented with unique_ptr is appropriate.
source share