---
title: "C++知识点与问题"
author: "Perrin Yong"
author_profile: https://www.pystone.net/profile/
published_by: "Perrin Yong"
canonical: https://www.pystone.net/notes/cpp-faq-and-notes/
type: note
content_role: unspecified
visibility: public
id_stability: rename-stable
source_path: "10-计算机、信息技术与工程/02-编程语言与运行时/C++/C++知识点与问题.md"
content_hash: ef7792611582a4f3086846d923e8a87ac440cef78ef716bbbb351ec4819faa8f
knowledge_version: 224c990773de.5fa8af6e39fa
site_commit: 224c990773de166d23a886306577dd90379529ce
notes_commit: 5fa8af6e39fa3891d1b9b4832bfa6c4e0ecaaf0a
---
# C++知识点与问题

> 创建时间：2024/1/13 20:30

## 构造函数不能声明为虚函数

1）因为创建一个对象时需要确定对象的类型，而虚函数是在运行时确定其类型的。而在构造一个对象时，由于对象还未创建成功，编译器无法知道对象的实际类型，是类本身还是类的派生类等等
2）虚函数的调用需要虚函数表指针，而该指针存放在对象的内存空间中；若构造函数声明为虚函数，那么由于对象还未创建，还没有内存空间，更没有虚函数表地址用来调用虚函数即构造函数了

## 析构函数最好声明为虚函数

首先析构函数可以为虚函数，当析构一个指向派生类的基类指针时，最好将基类的析构函数声明为虚函数，否则可以存在内存泄露的问题。
如果析构函数不被声明成虚函数，则编译器实施静态绑定，在删除指向派生类的基类指针时，只会调用基类的析构函数而不调用派生类析构函数，这样就会造成派生类对象析构不完全。

## 函数不能返回局部变量的指针或引用的问题

## 原因

不要返回函数体内局部变量的地址，因为函数结束时栈会回收，局部变量也随之销毁（如果局部变量为类对象，其析构函数会被自动调用），但可以返回局部变量本身。

错误示例

```cpp
string str1 = &quot;test&quot;;
string str2 = &quot;test&quot;;

```

## 解决方法

### 使用全局数组。使用全局变量时，在程序结束时才释放。

### 使用new/malloc在堆上动态分配内存

> 不要忘记了，在使用完后要进行内存的释放，不然会造成内存的泄漏。分别用delete,free(),释放。使用delete时，会调用类的析构函数，而free则不会。

```cpp
string str1 = &quot;test&quot;;
string str2 = &quot;test&quot;;

```

### 定义为静态类型

```cpp
string str1 = &quot;test&quot;;
string str2 = &quot;test&quot;;

```

### 用String类型

用string实现，是值拷贝!不存在释放内存会影响拷贝的问题。

```cpp
string str1 = &quot;test&quot;;
string str2 = &quot;test&quot;;

```

### 使用字符串常量

字符串常量存储在静态存储区域，所以一直都存在

```cpp
string str1 = &quot;test&quot;;
string str2 = &quot;test&quot;;

```

### 在调用函数中定义指针

```cpp
string str1 = &quot;test&quot;;
string str2 = &quot;test&quot;;

```

## Ref

https://blog.csdn.net/xuyunyunaixuexi/article/details/81989201
