在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;
}