So as I understand it you can return objects in C++ by returning pointers to them. But I was under the impression that once a function is finished running, the destructor gets called on all the objects. Why doesn’t the destructor get called on the object you’re returning?
Share
Only the destructors of objects with automatic storage duration are called when those objects leave their scope (not just a function, but any scope: braces,
for-statements, even single-line expressions).On the other hand, objects of static storage duration are only destroyed at program exit, and objects of dynamic storage duration (i.e. those created with a
newoperator) only get destroyed manually on your request.When you return a pointer in the way you describe, then almost surely that pointer points to a dynamically created object, and thus it is the responsibility of the recipient of the pointer to see to it that the object is eventually cleaned up. This is the great disadvantage of naked pointers: They do not convey any implicit ownership statement, and you have to provide the information about who’s responsible for the dynamic object manually outside the code.