No, this is a specifically bad use of new
.
If you must use new
and delete
1, use them as bookends. The delete expression should be in a logically consistent context with the new expression.
So, if you new
in a c-tor, you should delete
in the d-tor. If you new
in an allocation function, you should delete
in a deallocation function. The two calls should be arranged in an way that makes it obvious that one starts an operation and the other finishes it.
This implies that the call to new
and delete
should exist in the same layer in a functional or object hierarchy. Specifically, new
and delete
should be seen as implementation details, and not as part of the API contract.2
In your case, the new and delete are in entirely distinct contexts. new
is inside the implementation, while delete
is called for in the client. This will lead to programming errors.
Beyond that, the non-new version of your code (creating empty vectors in main
, and passing them by reference) is simpler, easier to read, and more exception-friendly than the new
version.
No, this is not a good example of when to use new
. It is, however, an excellent example of when not to.
1 You hardly ever need to use new
and delete
. If you need dynamic allocation, just let containers keep copies of your objects.
2 std::shared_ptr
, et al, violate this rule -- the new
and delete
are specifically part of the contract. This is probably OK, since pointer manipulation is their reason for existence. But SO has seen its share of bugs about storing a non-new
pointer in shared_ptr
.