在Ubuntu环境下,使用C++智能指针可以有效地管理内存资源,避免内存泄漏。C++11引入了智能指针,包括std::unique_ptr
、std::shared_ptr
和std::weak_ptr
。下面是如何在Ubuntu环境下使用这些智能指针的示例:
std::unique_ptr
std::unique_ptr
是一种独占所有权的智能指针,它确保同一时间只有一个指针可以指向某个对象。
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor" << std::endl; }
~MyClass() { std::cout << "MyClass destructor" << std::endl; }
};
int main() {
std::unique_ptr<MyClass> ptr(new MyClass());
// 使用ptr
// ...
// 当ptr离开作用域时,MyClass对象会被自动删除
return 0;
}
std::shared_ptr
std::shared_ptr
允许多个指针共享同一个对象的所有权。当最后一个shared_ptr
被销毁时,对象会被自动删除。
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() { std::cout << "MyClass constructor" << std::endl; }
~MyClass() { std::cout << "MyClass destructor" << std::endl; }
};
int main() {
std::shared_ptr<MyClass> ptr1(new MyClass());
{
std::shared_ptr<MyClass> ptr2 = ptr1;
// 使用ptr1和ptr2
// ...
} // ptr2离开作用域,但ptr1仍然有效
// 使用ptr1
// ...
// 当ptr1离开作用域时,MyClass对象会被自动删除
return 0;
}
std::weak_ptr
std::weak_ptr
是一种弱引用智能指针,它不会增加对象的引用计数。std::weak_ptr
通常与std::shared_ptr
一起使用,以避免循环引用导致的内存泄漏。
#include <iostream>
#include <memory>
class B;
class A {
public:
std::shared_ptr<B> b_ptr;
~A() { std::cout << "A destructor" << std::endl; }
};
class B {
public:
std::weak_ptr<A> a_ptr; // 使用weak_ptr避免循环引用
~B() { std::cout << "B destructor" << std::endl; }
};
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
std::shared_ptr<B> b = std::make_shared<B>();
a->b_ptr = b;
b->a_ptr = a;
// 使用a和b
// ...
// 当a和b离开作用域时,A和B对象会被自动删除
return 0;
}
在Ubuntu环境下,你可以使用g++编译器来编译和运行这些示例代码。例如:
g++ -std=c++11 -o smart_ptr_example smart_ptr_example.cpp
./smart_ptr_example
确保你的编译器支持C++11或更高版本,因为智能指针是在C++11中引入的。