当在C++中处理动态内存分配时,使用智能指针是一种良好的实践,可以帮助避免内存泄漏和悬空指针等问题。C++11引入了三种主要的智能指针:std::unique_ptr、std::shared_ptr和std::weak_ptr。下面是一个简单的代码演示,展示如何使用std::unique_ptr和std::shared_ptr:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass(int val) : value(val) {
std::cout << "Constructor called. Value: " << value << std::endl;
}
~MyClass() {
std::cout << "Destructor called. Value: " << value << std::endl;
}
void setValue(int val) {
value = val;
}
int getValue() const {
return value;
}
private:
int value;
};
int main() {
// 使用 std::unique_ptr
std::unique_ptr<MyClass> uniquePtr(new MyClass(42));
uniquePtr->setValue(100);
std::cout << "Value using unique_ptr: " << uniquePtr->getValue() << std::endl;
// 使用 std::shared_ptr
std::shared_ptr<MyClass> sharedPtr = std::make_shared<MyClass>(10);
sharedPtr->setValue(200);
std::cout << "Value using shared_ptr: " << sharedPtr->getValue() << std::endl;
// shared_ptr 的引用计数
std::cout << "shared_ptr use count: " << sharedPtr.use_count() << std::endl;
// shared_ptr 的复制
std::shared_ptr<MyClass> sharedPtr2 = sharedPtr;
std::cout << "shared_ptr use count after copy: " << sharedPtr.use_count() << std::endl;
std::weak_ptr<MyClass> weakPtr = sharedPtr;
if (auto shared = weakPtr.lock()) {
std::cout << "Value using weak_ptr: " << shared->getValue() << std::endl;
} else {
std::cout << "Object no longer exists" << std::endl;
}
sharedPtr.reset();
if (auto shared = weakPtr.lock()) {
std::cout << "Value using weak_ptr after shared_ptr reset: " << shared->getValue() << std::endl;
} else {
std::cout << "Object no longer exists" << std::endl;
}
return 0;
return 0;
}
在这个示例中,我们创建了一个简单