gpt4 book ai didi

c++ - 为什么 C++ new 不返回指向它创建的对象的指针?

转载 作者:太空狗 更新时间:2023-10-29 19:52:23 26 4
gpt4 key购买 nike

我正在理解以下代码,据我所知,当我使用 new 声明一个对象时,它会构造一个特定类型的对象并返回指向该对象的指针。但是在这里,当我使用 new 创建一个学生对象时,它不会返回指向该对象的指针。此外,当我调用 new student(s1) 时,“student(student* s)” 被调用而不是给出错误,例如没有从学生到学生的类型转换*

#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);
}

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

cool:2

最佳答案

你正在泄漏内存。

这个构造函数:

student(student* s)

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

student s1=new student();

是不是你堆分配了一个新的 student 对象。 new 表达式计算为一个指针。当编译器查看赋值时,它知道赋值不起作用,因为 s1 是一个 student 而你正在赋值一个 student *给它。所以它四处寻找一种方法来转换它并找到我上面提到的构造函数。

所以你所做的相当于:

student s1 = student(new student());

由于您从未删除 指针,因此堆分配已泄漏,但从您的角度来看,您的程序执行正确。

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

explicit student(student* s)

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

关于c++ - 为什么 C++ new 不返回指向它创建的对象的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26263047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com