How can I initialize vector<type*> in my class?

102 Views Asked by At

Why does it have 1000 elements?

class node 
{
  public:
    std::vector<node*> symbs;
    int count = 0;

    node() : count(0), symbs(26, nullptr) {}

};
int main()
{
    node *trees;
}

enter image description here

I can use node *trees = new node; and it's ok, but I don't want to clean memory. How can I do it differently?

1

There are 1 best solutions below

0
Slava On

Why it has 1000 elements?

You have uninitialized pointer which you use to access some random memory and get garbage result aka Undefined Behavior.

I can use node *trees = new node; and it's ok, but i don't want clean memory. How can I do it in a different way?

You can just create object, not pointer to it:

int main()
{
    node trees;
}

This object will be created at the point of definition and automatically destroyed at the end of the scope.

As for your vector, if your node object owns that sub-nodes it should contain a vector of std::unique_pointer<node> or std::shared_pointer<node> depends on ownership. Note - ownership means that 2 nodes should not own each other, otherwise you will get cyclic refernce and memory leak. Using smart pointers you do not have to create and implement destructor and copy/move costructor etc.