删除:如何定义一个只能在堆上(栈上)生成对象的类?

https://github.com/huihut/interview/issues/112
This commit is contained in:
huihut
2025-07-26 21:58:43 +08:00
parent 8871b8ffa8
commit cb34d14bc7
2 changed files with 0 additions and 32 deletions

View File

@@ -1026,22 +1026,6 @@ new (place_address) type [size] { braced initializer list }
3. 必须保证成员函数的 `delete this ` 后面没有调用 this 了
4. 必须保证 `delete this` 后没有人使用了
### 如何定义一个只能在堆上(栈上)生成对象的类?
> [如何定义一个只能在堆上(栈上)生成对象的类?](https://www.nowcoder.com/questionTerminal/0a584aa13f804f3ea72b442a065a7618)
#### 只能在堆上
方法:将析构函数设置为私有
原因C++ 是静态绑定语言,编译器管理栈上对象的生命周期,编译器在为类对象分配栈空间时,会先检查类的析构函数的访问性。若析构函数不可访问,则不能在栈上创建对象。
#### 只能在栈上
方法:将 new 和 delete 重载为私有
原因:在堆上生成对象,使用 new 关键词操作,其过程分为两阶段:第一阶段,使用 new 在堆上寻找可用内存,分配给对象;第二阶段,调用构造函数生成对象。将 new 操作设置为私有,那么第一阶段就无法完成,就不能够在堆上生成对象。
### 智能指针
#### C++ 标准库STL

View File

@@ -1031,22 +1031,6 @@ Legal, but:
3. You must ensure that the member function does not call this after `delete this`
4. Make sure no one uses it after delete this
### How to define a class that can only generate objects on the heap (on the stack)?
> [How to define a class that can only generate objects on the heap (on the stack)?](https://www.nowcoder.com/questionTerminal/0a584aa13f804f3ea72b442a065a7618)
#### Only on the heap
Method: Make the destructor private
Reason: C ++ is a static binding language. The compiler manages the life cycle of objects on the stack. When the compiler allocates stack space for class objects, it first checks the accessibility of the class's destructor. If the destructor is not accessible, the object cannot be created on the stack.
#### Only on the stack
Method: overload new and delete as private
Reason: The object is generated on the heap using the new keyword operation. The process is divided into two stages: the first stage uses new to find available memory on the heap and allocates it to the object; the second stage calls the constructor to generate the object. By setting the new operation to private, the first phase cannot be completed, and objects cannot be generated on the heap.
### Smart pointer
#### In the C ++ Standard Library (STL)