一、this
?關鍵字
1. 什么是?this
?
this
?是 C++ 中的一個隱式指針,它指向當前對象(即調用成員函數的對象),在成員函數內部使用,用于引用調用該函數的對象。每個類的非靜態成員函數內部都可以使用?this
。
使用 this 可以明確指出成員函數正在操作的是哪個對象的數據成員。
2. 為什么需要?this
?
當成員函數的參數名與成員變量名相同時,可以用?this
?來區分。
示例代碼:
#include <iostream>
using namespace std;class Person {
private:string name;int age;public:// 構造函數,參數名與成員變量名相同Person(string name, int age) {this->name = name; // 用 this 區分成員變量和參數this->age = age;}void printInfo() {// this 可以省略,但顯式使用更清晰cout << "Name: " << this->name << ", Age: " << this->age << endl;}// 返回當前對象的引用(用于鏈式調用)Person& setName(string name) {this->name = name;return *this; // 返回當前對象本身}
};int main() {Person p("Alice", 25);p.printInfo(); // 輸出: Name: Alice, Age: 25// 鏈式調用p.setName("Bob").printInfo(); // 輸出: Name: Bob, Age: 25return 0;
}
代碼解釋:
- 在構造函數中,參數名?
name
?和?age
?與成員變量同名,用?this->name
?表示成員變量。 printInfo()
?中?this
?可以省略,但顯式使用讓代碼更清晰。setName()
?返回?*this
(即當前對象的引用),支持鏈式調用。
3.?this
?的其他用途
- 傳遞當前對象給其他函數
- 在成員函數中返回當前對象本身
- 解決局部變量與成員變量同名的問題
示例:
class Example {int value;
public:Example(int value) {this->value = value; // 區分成員變量和參數}void show() {cout << "Value: " << value << endl; // 等價于 this->value}Example& increment() {this->value++; // 修改當前對象的成員return *this; // 返回當前對象本身}
};
4.?this
?的注意事項
this
?是指針,不是引用(*this
?才是當前對象的引用)- 靜態成員函數中沒有?
this
(因為靜態函數不屬于任何對象) - 不要隨意返回?
this
?的指針(可能導致懸空指針)
二、new
?關鍵字
1. 什么是?new
?
new
?是 C++ 中用于動態內存分配的運算符,它在堆(heap)上創建對象并返回指針。
2. 為什么需要?new
?
- 在程序運行時(而非編譯時)決定內存分配
- 創建的對象生命周期不受作用域限制
- 可以創建大型對象(棧空間可能不足)
3. 基本用法
示例代碼:
#include <iostream>
using namespace std;class Dog {string name;int age;
public:Dog(string n, int a) : name(n), age(a) {}void bark() {cout << name << " says: Woof! I'm " << age << " years old." << endl;}~Dog() {cout << name << " is being destroyed." << endl;}
};int main() {// 在堆上創建 Dog 對象Dog* myDog = new Dog("Buddy", 3);myDog->bark(); // 輸出: Buddy says: Woof! I'm 3 years old.// 必須手動釋放內存delete myDog; // 輸出: Buddy is being destroyed.return 0;
}
代碼解釋:
new Dog("Buddy", 3)
?在堆上創建對象,返回指向它的指針。- 通過指針訪問成員用?
->
?運算符。 delete
?釋放內存并調用析構函數。
4.?new
?的高級用法
動態數組分配:
int main() {// 動態分配包含 5 個 int 的數組int* arr = new int[5];for (int i = 0; i < 5; i++) {arr[i] = i * 10; // 賦值}for (int i = 0; i < 5; i++) {cout << arr[i] << " "; // 輸出: 0 10 20 30 40}cout << endl;// 釋放數組要用 delete[]delete[] arr;return 0;
}
注意事項:
- 數組必須用?
delete[]
?釋放,單個對象用?delete
。 - 忘記釋放會導致內存泄漏。
5.?new
?的替代方案(現代 C++)
使用智能指針(推薦):
#include <memory>int main() {// 自動管理內存的 unique_ptrunique_ptr<Dog> smartDog(new Dog("Max", 4));smartDog->bark();// 不需要手動 delete,離開作用域自動釋放// 更安全的 make_unique (C++14)auto smartDog2 = make_unique<Dog>("Charlie", 5);smartDog2->bark();return 0;
}
6.?new
?的注意事項
必須配對使用?
delete
:
int* p = new int; // 分配
*p = 10;
delete p; // 釋放
- 避免內存泄漏:
void leakyFunction() {int* leak = new int[100]; // 分配但未釋放// 如果中間發生異常,delete 永遠不會執行
} // 內存泄漏!
- 不要重復釋放:
int* p = new int;
delete p; // 正確
delete p; // 錯誤!未定義行為
檢查分配是否成功(現代 C++ 中?
new
?失敗會拋出?std::bad_alloc
?異常)初始化分配的內存:
// C++11 統一初始化
int* p1 = new int{42}; // 值初始化為 42// 默認初始化(值不確定)
int* p2 = new int;// 動態數組初始化為 0
int* arr = new int[10](); // 所有元素初始化為 0
三、總結對比
特性 | this ?關鍵字 | new ?運算符 |
---|---|---|
作用 | 指向當前對象 | 動態分配內存 |
返回值 | 當前對象的指針 | 新分配內存的指針 |
使用場景 | 成員函數中訪問當前對象 | 需要運行時決定內存分配時 |
內存位置 | 不適用(是指針) | 堆(heap) |
生命周期 | 不適用 | 直到顯式?delete ?或程序結束 |
錯誤風險 | 誤用可能導致邏輯錯誤 | 忘記釋放導致內存泄漏 |
最佳實踐建議:
this
?使用建議:- 在成員變量和參數同名時使用
- 需要返回當前對象時(鏈式調用)
- 避免過度使用,保持代碼清晰
new
?使用建議:- 優先考慮棧分配或智能指針
- 如果必須用?
new
,確保有對應的?delete
- 對于數組,使用?
std::vector
?代替?new[]
- 在 C++11+ 中,優先使用?
std::make_unique
/std::make_shared
- 現代 C++ 趨勢:
- 減少裸?
new
/delete
?的使用 - 使用 RAII(資源獲取即初始化)原則
- 依賴標準庫容器和智能指針管理資源
- 減少裸?