面试题答案
一键面试在C++中,可以使用智能指针来有效防止重复释放同一块内存并避免产生野指针。以std::unique_ptr
为例,它是一种独占式智能指针,当std::unique_ptr
离开其作用域时,它会自动释放所指向的内存。
代码示例如下:
#include <iostream>
#include <memory>
int main() {
// 使用std::unique_ptr分配内存
std::unique_ptr<int> ptr(new int(42));
// 访问内存中的值
std::cout << "Value: " << *ptr << std::endl;
// std::unique_ptr离开作用域时,内存会自动释放,无需手动delete
return 0;
}
如果使用std::shared_ptr
,它是一种共享式智能指针,通过引用计数来管理内存,当引用计数为0时,内存会自动释放。
代码示例如下:
#include <iostream>
#include <memory>
int main() {
// 使用std::shared_ptr分配内存
std::shared_ptr<int> ptr1(new int(42));
std::shared_ptr<int> ptr2 = ptr1; // 共享所有权,引用计数增加
// 访问内存中的值
std::cout << "Value: " << *ptr1 << std::endl;
std::cout << "Value: " << *ptr2 << std::endl;
// ptr1和ptr2离开作用域时,引用计数减1,当引用计数为0时内存自动释放
return 0;
}