是否可以构造一个指针类型,其行为和行为(就语法而言)像普通指针一样,除了你不能对它调用 delete (可能使用预处理器宏)?
示例用法:
borrowed_ptr<int> ptr = new int[42];
ptr[12] = 1;
cout<<ptr[12]<<endl; //prints 1
delete ptr; //error: no operator delete for borrowed_ptr<int>
borrowed_ptr<int> ptr2 = new int(2);
delete ptr2; //error
这也应该工作
template<typename t>
void func(borrowed_ptr<t> *arg)
{
delete arg; //error
}
//somewhere else
int *t = new *int;
func(t);
但是,“反向分配”不应该起作用。
borrowed_ptr<int> foo = new int(2);
int* bar = foo; //error
声明借用_ptr 时是否需要 * 对我来说并不重要。像这样的代码很重要
template <typename T>
void foo(T* whatever)
{
//do something with whatever
delete whatever;
}
template <typename T>
void bar(T* whatever)
{
//do something with whatever
}
可以像这样使用这个 borrowed_ptr 调用:
borrowed_ptr<int> a = new int(2);
foo(a); //error, function tries to delete
bar(a); //fine, and has the same semantics as handing over a raw int*
注意:当指针类型为删除本身时,我不希望删除数据。它应该只是一个借来的ptr,因为它属于别人,所以不能删除。