简体   繁体   中英

Why doesn't the destructor get called on objects you are returning?

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?

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 (ie those created with a new operator) 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.

The destructor for an object you created with new doesn't get called until you delete the pointer.

To make sure you don't forget to delete the pointer, try using smart pointers such as std::shared_ptr or std::unique_ptr .

If your compiler isn't new enough to include smart pointers, you can find some from Boost .

当您返回对对象的引用时,该引用将不再作用于函数,因此不会随函数失效(即,不会删除指向对象的指针)。

That would only happen if you wrote code incorrectly. For example:

Foo* MyFunction()
{
    Foo foo(2);
    return &foo;
} // foo is implicitly destroyed as we return

This is broken. I take the address of foo , but it is also destroyed because it goes out of scope. This is fine:

Foo* MyFunction()
{
    Foo* j=new Foo(2);
    return j;
} // j is implicitly destroyed as we return

This is fine. While j is destroyed because it goes out of scope, the value that I returned is still the address of the Foo I created. The foo that I allocated will not be destroyed because it doesn't go out of scope.

There are two ways of allocating objects: the stack and the heap.

1) Objects are created on the heap with the new keyword. These objects are not destroyed until they are delete d.

2) Other objects exist on the stack - no new , no delete . These objects are destroyed when they go out of scope. If you return a pointer to one of these objects (by taking the address of a stack-allocated object, the pointer will be invalid once the object has gone out of scope.

C ++(。net外部)在您告知对象之前不会删除对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM