C++中如果动态分配的内存没有被正确的删除,那么就会导致内存泄漏,例如以下代码:
void f() {
int *p = new int(3);
std::cout << *p << std::endl;
} 当p超出作用域后,由于没有被手动删除,因此会导致内存泄漏。
请设计一个scope pointer:ScopedPtr,其具有以下特点:
1. 使用一个动态分配的int初始化(构造函数)。
2. 当该scope pointer超出作用域后,会自动释放动态分配的内存。
3. 可以通过解引用操作符获取到该动态分配的int的引用。
4. 该scope pointer不能被复制。
请实现该ScopedPtr,可以让以下代码编译通过正常运行:
#include <iostream>
class ScopedPtr {
};
void test(int n) {
ScopedPtr ptr(new int(n));
*ptr *= 2;
std::cout << *ptr << std::endl;
}
int main () {
int n = 0;
std::cin >> n;
test(n);
return 0;
}

