this is quite error prone code. If an error happens somewhere in the middle of function and exception is thrown, the memory is leaked. The solution would be to have simple vectors "w, p, n" instead of pointers or use smart pointer Ptr&lt;&gt;