为什么C++ new没有返回指向它创建的对象的指针?

roc*_*cko 3 c++ oop

我理解下面的代码,根据我的知识,当我使用new声明一个对象时,它构造一个特定类型的对象并返回指向该对象的指针.但是当我使用new创建一个student对象时,它不会返回指向该对象的指针.此外,当我打电话给新学生时(s1), " 学生(学生*) "被称为" 学生(学生) ",而不是给出错误,例如没有从学生到学生的类型转换*

#include <bits/stdc++.h>

using namespace std;

class student {
    public:
        int cool;

        student(student* s){ // this constructor is taking pointer to s whereas i am calling it by value below
            this->cool=s->cool;
        }
        student(){
            this->cool=1;
        }
};
void blah(student s){
    printf("cool:%d\n",s.cool);
}

int main(){

    student s1=new student(); // here new is not returning student*
    s1.cool=2;
    student s2=new student(s1); // here we are passing s1 which of type student but constructor (student*) is called why ???
    blah(s2);
}
Run Code Online (Sandbox Code Playgroud)

以下输出我得到没有任何错误:

酷:2

cdh*_*wie 7

你在泄漏记忆.

这个构造函数:

student(student* s)
Run Code Online (Sandbox Code Playgroud)

用于隐式地满足转换,因为它没有标记explicit.那么这里发生了什么:

student s1=new student();
Run Code Online (Sandbox Code Playgroud)

是你堆 - 分配一个新student对象.所述new表达式的计算结果的指针.当编译器查看赋值时,它知道赋值将不起作用,因为它s1是a student并且您正在student *为其赋值.所以它寻找一种方法来转换它并找到我上面提到的构造函数.

所以你所做的相当于:

student s1 = student(new student());
Run Code Online (Sandbox Code Playgroud)

由于您从不delete指针,因此堆分配被泄露,但从您的角度来看,您的程序正确执行.

如果您将转换构造函数标记如下:

explicit student(student* s)
Run Code Online (Sandbox Code Playgroud)

然后编译器不会自动使用这个构造函数进行转换,需要显式调用某种类型,并且该行student s1=new student();确实会导致编译时错误,同时允许student s1 = student(new student());工作(但当然它仍然会导致内存泄漏).