您的位置:首页技术文章
文章详情页

java - 是否类 类型指针、引用作为形参 ,函数结束不会自动析构类?

浏览:88日期:2024-01-19 18:07:19

问题描述

自动析构是在作用域结束时析构作用域里创建的类对象的吗?

问题解答

回答1:

如果是用指针new出来的对象, 必须进行手动delete. 析构函数不会帮你自动析构, 比如std::string* s = new std::string;. 如果这是在一个类里面构造的string, 这个类会将s回收, 但是不会将s指向的空间回收. 引用你只要记住其实就是一个别名就能做出自己的判断了.

回答2:

我不该讲那么多有的没的,而且我理解的不对。

在函数结束时,只有声明在函数体内的自动变量和函数的形式参数会被销毁(destroyed),他们所引用的对象(若有),不会随他们的销毁而被销毁。一个指针/引用所引用的对象有自己独立的存储期,这个对象何时被销毁,取决于它自己的存储期。

你在问题中问的是何时隐式调用析构函数。析构函数的隐式调用同样取决于这个对象的存储期。简单的说,若对象被构造,则析构函数会在他被销毁时被调用。

12.3.2.11 Destructors are invoked implicitly— for constructed objects with static storage duration (3.7.1) at program termination (3.6.3),— for constructed objects with thread storage duration (3.7.2) at thread exit,— for constructed objects with automatic storage duration (3.7.3) when the block in which an object is created exits (6.7),— for constructed temporary objects when the lifetime of a temporary object ends (12.2),— for constructed objects allocated by a new-expression (5.3.4), through use of a delete-expression (5.3.5),— in several situations due to the handling of exceptions (15.3).

关于引用:

引用不是对象,但他同样有存储期(存储期对任何变量都适用)。存储期的销毁规则同样适用于引用。但是在引用被销毁时发生什么,我没有找到准确的描述。究竟引用如何被销毁应该是取决于编译器实现。大概情况应该是:如果引用在实现时占有存储空间,则该空间会被回收。如果不占有,则什么都不会发生。(引用类型的形式参数在函数不被内联时常常会占有存储空间)

3.7.3 The storage duration categories apply to references as well. The lifetime of a reference is its storage duration.

8.3.2.4 It is unspecified whether or not a reference requires storage.

3.9.8 An object type is a (possibly cv-qualified) type that is not a function type, not a reference type, and not a void type.

1.8 [...] An object is a region of storage. [ Note: A function is not an object, regardless of whether or not it occupies storage in the way that objects do. — end note ] [...]

回答3:

1.析构函数是c++针对类引入的,是在类变量生命周期结束之后,空间被回收之前被调用的函数。2.类指针和类引用(指向变量的常指针)只是基本数据类型(指针),并没有析构函数之说,函数调用结束之后他们对应的栈空间会被回收而已。3.如果参数传递的是类对象则就如第一点说的那样,在空间被回收之前调用析构函数。4.所有的栈上的类变量都会在生命周期结束后自动析构,而堆上的类变量(new等操作分配的)则不会,需要手动释放去触发析构函数的调用。

标签: java