Jin Jung Jin Jung - 1 year ago 66
C++ Question

in c++, creating new constructor. how does this work when put into for loop?

for(unsigned int i = 0; i < max; i++) {
auto curr = new LinkedListNode(ptr1, ptr2, nullptr);

I am guessing, this will result in same as doing

auto curr = new LinkedListNode(ptr1, ptr2, nullptr);

like same result as not putting it through the loop.

how are they different??

Tas Tas
Answer Source

how are they different??

They're different in the sense that the code in the for loop will make max number of LinkedListNode, and the latter will only make a single LinkedListNode.

You can see this in action. Notice how many times the constructor is called for LinkedListNode, but the destructor is never called.

Your for loop is useless. It does nothing but leak memory. Even if you weren't manually managing memory, the for loop does nothing but create a bunch of objects you later have no access to since curr falls out of scope.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download