Skip to content

Commit cb34d14

Browse files
committed
删除:如何定义一个只能在堆上(栈上)生成对象的类?
#112
1 parent 8871b8f commit cb34d14

2 files changed

Lines changed: 0 additions & 32 deletions

File tree

README.md

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

README_en.md

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,22 +1031,6 @@ Legal, but:
10311031
3. You must ensure that the member function does not call this after `delete this`
10321032
4. Make sure no one uses it after delete this
10331033
1034-
### How to define a class that can only generate objects on the heap (on the stack)?
1035-
1036-
> [How to define a class that can only generate objects on the heap (on the stack)?](https://www.nowcoder.com/questionTerminal/0a584aa13f804f3ea72b442a065a7618)
1037-
1038-
#### Only on the heap
1039-
1040-
Method: Make the destructor private
1041-
1042-
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.
1043-
1044-
#### Only on the stack
1045-
1046-
Method: overload new and delete as private
1047-
1048-
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.
1049-
10501034
### Smart pointer
10511035
10521036
#### In the C ++ Standard Library (STL)

0 commit comments

Comments
 (0)