在Ubuntu上進行C++編程時,開發者可能會遇到一些常見的誤區或錯誤。了解這些誤區可以幫助開發者避免這些問題,從而提高代碼質量和編程效率。以下是一些常見的誤區及其解決方案:
內存泄漏:
int* ptr = new int;
// 忘記 delete ptr;
delete
釋放內存。空指針解引用:
int* ptr = nullptr;
*ptr = 10; // 空指針解引用
數組越界訪問:
int arr[5];
arr[5] = 10; // 越界訪問
使用未初始化的變量:
int num;
std::cout << num; // 未初始化的變量
誤用引用:
int& ref = *(new int);
delete &ref; // ref 成為懸空引用
nullptr
。忘記釋放資源:
FILE* file = fopen("example.txt", "r");
// 忘記 fclose(file);
類型轉換錯誤:
int num1 = 1000;
char ch = static_cast<char>(num1); // 數據溢出
忘記重載操作符:
class MyClass {
int* ptr;
public:
MyClass() : ptr(new int) {}
~MyClass() { delete ptr; }
// 忘記重載賦值運算符
};
循環迭代器失效:
std::vector<int> nums = {1, 2, 3, 4, 5};
for (auto it = nums.begin(); it != nums.end(); ++it) {
nums.push_back(6); // 循環迭代器失效
}
線程同步問題:
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
mutex mtx;
void printNumber(int num) {
mtx.lock();
std::cout << num << std::endl;
mtx.unlock();
}
int main() {
thread t1(printNumber, 1);
thread t2(printNumber, 2);
t1.join();
t2.join();
return 0;
}
緩沖區溢出:
strcpy
。例如:char str[10];
strcpy(str, "this is a very long string."); // 可能造成緩沖區溢出
strncpy
或 std::string
(C++11 及以上)。懸掛指針:
int* p = new int(5);
delete p;
*p = 10; // 懸掛指針,可能導致段錯誤
nullptr
。未捕獲的異常:
void maythrowexception() {
throw std::runtime_error("an error occurred.");
}
int main() {
maythrowexception(); // 如果沒有捕獲,程序會終止
return 0;
}
try-catch
塊,并妥善處理異常。浮點數精度丟失:
double a = 0.1;
double b = 0.2;
if (a + b == 0.3) {
// 浮點數精度問題
}
無符號整數溢出:
unsigned int num = UINT_MAX;
num++; // 溢出
隱式類型轉換:
int num1 = 1000;
double num2 = num1; // 隱式整數到浮點數的轉換
全局對象的時序和作用域問題:
int globalVar;
void func() {
globalVar = 10;
}
int main() {
func();
// globalVar 的值可能未定義
}
函數參數的默認值寫到函數實現中了:
BOOL CreateConf(const CString& strConfName, const BOOL bAudio = FALSE);
在編寫類的時候,在類的結尾處忘記添加 “;” 分號了:
class Shape {
// ...
};
只添加了函數聲明,沒有函數實現在添加類的函數時,只在類的頭文件中添加了函數聲明,但在 cpp 中卻沒有添加函數的實現:
unresolved external symbol
錯誤。例如:class MyClass {
void func();
};
cpp 文件忘記添加到工程中,導致沒有生成供鏈接使用的 obj 文件:
// MyClass.h
void func();
// MyClass.cpp
#include "MyClass.h"
void MyClass::func() {
// 實現
}
函數中返回了一個局部變量的地址或者引用:
char* GetResult() {
char chResult[100] = {0};
return chResult;
}