在C ++ std::allocator
中,有三种与常见概念相关的方法:
deallocate
destroy
我想知道:
谢谢!
编辑:更具体的疑惑:
我很抱歉首先概括一下,这里有一点我不明白。
destroy
用于调用对象上的析构函数,"对象"这意味着什么?再次感谢你!
答案 0 :(得分:4)
cppreference.com documentation的简短描述只是为我解释了差异
“1。析构函数做什么?文档没有讨论在调用析构函数时是否会自动释放内存”
std::allocator
实例占用的任何内存都将照常释放。
“2.
destroy
用于调用对象上的析构函数,这里的”对象“是什么意思?”
再次引用详细文档
void destroy( pointer p ); // 1)
template< class U > // 2)
void destroy( U* p );
此上下文中的调用p
_指向的对象的析构函数 1)致电((T*)p)->~T()
2)致电p->~U()
Object 表示由T
实例管理的std::allocator
类型的对象。
答案 1 :(得分:0)
你的问题的答案在于删除操作和对象析构函数之间的关系。
deallocate(指针p,size_type大小)
- calls "delete p";
- "delete" implicitly calls the destructor of the object at p;
- frees/deallocates the memory where the object pointed by p was stored
销毁(指针p)
- calls only the destructor ((T*)p)->~T()
- the memory at addres p will not be freed/deallocated
关于析构函数
为什么在不使用delete的情况下调用析构函数是有意义的?
一个dinamically分配的对象可以有指向已分配对象的指针作为成员变量。如果你想释放那个内存而不删除保存指针的原始对象,你可以调用overriden析构函数,因为 默认的不会这样做。
在下面的示例中,我将尝试轻视上述问题。
示例:
template < class T,class U >
class MyClass{
private:
T* first_pointer;
U* second_pointer;
public:
MyClass(){ //constructor:
first_pointer=new T(); //allocate memory for pointer variables
second_pointer=new U(); //with non-argument constructors T() and U()
}
~MyClass(){ //destructor is overriden
delete first_pointer; //because the default-destructor
delete second_pointer; //will not release the memory allocated for
} //first_pointer and second_pointer
void set_first(const T& val){
first_pointer=new T(val);
}
void set_second(const U& val){
second_pointer=new U(val);
}
};
void some_function(void){
MyClass *object;
object=new MyClass();//for example:the allocated object is at memory location 00123A
//lets say that after some time you dont need the memory for "first_pointer" and
//"second_pointer" but you want to keep the memory for "object".
//so we call the destructor.
object->~MyClass();//memory at addres 00123A is still reserved for our object
//but the first_pointer and second_pointer locations
//are deallocated.
//then lets say that after some time we need to set the member variables
object->set_first(T(...)) //arguments depend on the defined constructors
object->set_second(U(...)) //for T and U. Doesn't really matter in this example
//after some time we dont need the object and it's parts at all
//so we call delete on the object
delete object; //calls our destructor to release the memory pointed to
//by first_pointer and second_pointer.
//then it deallocates the memory at "00123A" where our object was
}
现在回到std :: allocator和destroy()vs deallocate()
allocator是内存分配的抽象(接口)。 它将分配与破坏,解除分配与破坏分开。
destroy() - “破坏”内存位置上的数据,使对象不可用,但内存 仍在那里使用(可以再次构建对象)
deallocate() - “释放”对象所在的内存位置, 这样存储就不能用于构造对象 在这个位置再次。在此处输入代码