首页 > 试题广场 >

设计一个scope pointer

[编程题]设计一个scope pointer
  • 热度指数:110 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
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;
}


输入描述:
一个整数:N


输出描述:
一个整数:N * 2
示例1

输入

10

输出

20
实际上就是实现一个unique_ptr
#include <iostream>
using namespace std;

class ScopedPtr {
public:
	ScopedPtr(int* add):_add(add){}
	~ScopedPtr()
	{
		delete _add;
	}

        //注意这里返回的是引用,如果返回的不是引用的话
        //底下代码*ptr *= 2的左值就是一个不可修改的常量
	int& operator *() {
		return *_add;
	}

	int operator *=(int n) {
		return (*_add) * n;
	}

	int *_add;
};

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


编辑于 2021-04-08 21:43:44 回复(0)
#include <iostream>
usingnamespacestd;
 
 
classScopePtr {
public:
 
    ScopePtr(int* value):ptr(value)
    {
         
    }
    ~ScopePtr()
    {
        if(!ptr)
        {
            deleteptr;
            ptr = nullptr;
        }
 
    }
    int& operator*()
    {
        return*ptr;
    }
 
    ScopePtr(constScopePtr& s) = delete;
    ScopePtr& operator=(constScopePtr& s) = delete;
 
private:
    int* ptr;
};
 
 
 
voidtest(intn) {
    ScopePtr ptr(newint(n));
 
    *ptr *= 2;
 
    std::cout << *ptr << std::endl;
}
 
intmain() {
    intn = 0;
    cin >> n;
 
    test(n);
 
    return0;
}
发表于 2022-11-01 16:32:42 回复(0)