Skip to content

Commit 7419b95

Browse files
authored
Update cpp_tricks.md
1 parent d60f646 commit 7419b95

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

docs/cpp_tricks.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,73 @@ assert(stu2.name == "侯捷老师");
310310

311311
大多数情况下,我们只需要在类里面存 vector、string 等封装好的容器,编译器默认生成的拷贝构造函数会自动调用他们的拷贝构造函数,用户只需专注于业务逻辑即可,不需要操心底层细节。
312312

313+
对于持有资源的 RAII 类,我们都会直接删除其拷贝构造函数和拷贝赋值函数:
314+
315+
```cpp
316+
struct RAIIHandle {
317+
int handle;
318+
RAIIHandle() {
319+
handle = CreateObject();
320+
}
321+
RAIIHandle(RAIIHandle const &) = delete;
322+
RAIIHandle &operator=(RAIIHandle const &) = delete;
323+
RAIIHandle() {
324+
DeleteObject(handle);
325+
}
326+
};
327+
```
328+
329+
## 继承构造函数
330+
331+
C++ 特色:子类不会自动继承父类的构造函数!(除非父类的构造函数是没有参数的默认构造函数)
332+
333+
```cpp
334+
struct Parent {
335+
Parent(int age, const char *name) { ... }
336+
void parent_func() { ... }
337+
};
338+
339+
struct Child : Parent {
340+
void child_func() { ... }
341+
};
342+
343+
Child child(23, "peng"); // 错误!Child 没有构造函数!
344+
```
345+
346+
可以在子类里面写 `using 父类::父类`,就能自动继承父类所有的构造函数了。
347+
348+
```cpp
349+
struct Parent {
350+
Parent(int age, const char *name) { ... }
351+
void parent_func() { ... }
352+
};
353+
354+
struct Child : Parent {
355+
using Parent::Parent; // 加上这一行!
356+
void child_func() { ... }
357+
};
358+
359+
Child child(23, "peng"); // 编译通过,自动调用到父类的构造函数 Parent(int, const char *)
360+
```
361+
362+
在 C++98 中,没有 using 的这个语法,只能自己定义一个构造函数,然后使用“委任构造”的语法转发所有参数给父类,非常繁琐。
363+
364+
```cpp
365+
struct Parent {
366+
Parent(int age, const char *name) { ... }
367+
void parent_func() { ... }
368+
};
369+
370+
struct Child : Parent {
371+
Child(int age, const char *name)
372+
: Parent(age, name)
373+
{ ... }
374+
void child_func() { ... }
375+
};
376+
377+
Child child(23, "peng"); // 编译通过,调用到子类的构造函数后转发到父类
378+
```
379+
313380
## 提前返回
314381

315382
```cpp

0 commit comments

Comments
 (0)