在C编程中,您可以将任何类型的指针作为参数传递给free,它如何知道要释放的已分配内存的大小?每当我传递指向某个函数的指针时,我也必须传递大小(即10个元素的数组需要接收10作为参数来知道数组的大小),但我不必将大小传递给自由功能.为什么不,并且我可以在我自己的函数中使用相同的技术来避免需要购买数组长度的额外变量?
删除操作符如何工作?它比free()更好吗?如果你这样做ptr=new char[10],那么删除使用delete ptr,指针如何知道要删除多少个位置.
我不明白一件事.例如,我声明A类和B类是A的子类:
class A {
public:
int a;
}
class B : public A {
public:
int b;
}
Run Code Online (Sandbox Code Playgroud)
显然,如果我创建A或B的实例,它们在内存中的大小可以由类型确定.
A instanceA; // size of this will probably be the size of int (property a)
B instanceB; // size of this will probably be twice the size of int (properties a and b)
Run Code Online (Sandbox Code Playgroud)
但是如果我创建动态实例然后在以后释放它会怎样?
A * instanceAPointer = new A();
A * instanceBPointer = new B();
Run Code Online (Sandbox Code Playgroud)
这些是不同类的实例,但程序会将它们视为A类的实例.在使用它们时这很好但是如何释放它们呢?为了释放分配的内存,程序必须知道要释放的内存大小,对吧?
所以,如果我写
delete instanceAPointer;
delete isntanceBPointer;
Run Code Online (Sandbox Code Playgroud)
程序如何知道,有多少内存,从每个指针指向的地址开始,它应该是空闲的?因为很明显,对象具有不同的大小,但程序认为它们是A类型.
谢谢
几个月前,我问过这个问题,我问为什么会有内存泄漏.显然,我忘记了一个虚拟的析构函数.
现在我很难理解为什么这不是内存泄漏:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Base{
public:
explicit Base(double a){
a_ = a;
}
virtual void fun(){
cout << "Base " << a_ << endl;
}
protected:
double a_;
};
class Derived : public Base{
public:
Derived(double a, double b): Base(a), b_{b}{
}
void fun() override{
cout << "Derived " << a_ << endl;
}
private:
double b_;
};
int main() {
vector<unique_ptr<Base> > m;
for(int i=0; i<10; ++i){
if(i%2 == …Run Code Online (Sandbox Code Playgroud) c++ ×3
c ×1
free ×1
inheritance ×1
memory-leaks ×1
object ×1
oop ×1
pointers ×1
size ×1
unique-ptr ×1
valgrind ×1