int *p 和 int * p = new int; 之间有什么区别?

What is the difference betwene int *p and int * p = new int;

我有 3 个问题:

Q1。当我们使用 new 运算符创建对象时,语法如下:

pointer_variable = new data-type //To create an object
pointer_variable = new data-type(value); //To create an object with value 
pointer_variable = new data-type[size]; //To create an array

为什么 L.H.S 上总是有一个 pointer_variable?

Q2。使用和不使用 new 运算符声明和分配指针有什么区别?

考虑以下代码片段和输出以理解问题:

    int a = 10, b=20;
    int *p;
    p = &a;
    int *q = new int;
    q = &b;
    cout<<"P is: "<<p<<" : "<<*p<<endl<<"Q is: "<<q<<" : "<<*q<<endl;

以上代码的输出:

P is: 0x61ff04 : 10
Q is: 0x61ff00 : 20

Q3。当我们说,使用 new 运算符时,当我们在编译时不知道数组的大小时,我们可以在 运行 时动态地为数组分配内存。我们可以在没有 new 运算符的情况下执行此操作,如下所示:

    cout<<"Enter the size of an array"<<endl;
    int n;
    cin>>n;
    
    int arr[n];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    for(int i=0;i<n;i++)
    {
        cout<<arr[i];
    }

那么对数组使用new运算符到底有什么必要呢?

Why always there is a pointer_variable on L.H.S?

因为new-expression结果是一个指针。

What is the difference between declaring and assigning pointers with and without the new operator?

new-expression(不是 operator new)构造一个新对象(并可选地为其分配内存)。

We can do this without new operator as given below

事实上,根据 C++ 标准,我们不能。一些编译器只允许将此构造作为 non-standard 语言扩展 .

每个good C++ book for beginners会详细解释这些。

在 C++ 中,典型的 new 表达式在 上分配内存,returns 指向该内存的指针。

回复问题 1:您可以将结果指针保存到局部变量以供立即使用:pointer_variable = new int。但是您不必这样做:您可以将它用作函数的参数:use_pointer(new int).

回复问题 2:您的代码在堆上分配了一个 int,将其指针存储在局部变量 q 中,并立即用局部变量 b 的地址覆盖它。所以你在这里所做的是写一个小的内存泄漏。

关于问题 3:variable-sized 数组是 C++ 的非标准扩展,因此它不一定能在其他编译器中工作。但是,当它确实起作用时,它只是另一个自动变量:当您离开本地范围时,它将自动为 re-use de-allocated。这与 new 分配不同,后者持续到明确 delete-ed.