当函数返回指向类的指针时,是否会调用复制构造函数?
这个问题可能很愚蠢,但我想知道,当函数返回指向对象的指针时是否调用复制构造函数? 另外,考虑以下内容:
A* a1 = new A();
A* a = a1.GetPointer();
A* GetPoineter()
{
.....
return new A();
}
那么是否
A* a = a1.GetPointer();
调用复制构造函数?
另外,如果我删除a
,它也会删除a1
指向的地址吗?
This question might be silly, but I want to know, if a copy constructor is invoked when a pointer to an object is returned by a function?
Also,consider following:
A* a1 = new A();
A* a = a1.GetPointer();
A* GetPoineter()
{
.....
return new A();
}
so does
A* a = a1.GetPointer();
call copy constructor?
also if I delete a
, will it delete the address pointed by a1
also?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它不会调用复制构造函数,因为您返回的是对象的地址,而不是对象本身。
delete a;
只会删除在GetPoineter
函数中分配的对象。a1
未受影响,因为它指向一个完全不同的对象。No, it does not call the copy constructor since you are returning the address of the object, not the object itself.
delete a;
will only delete the object allocated in theGetPoineter
function.a1
is untouched since it points to a completely different object.编号
在您的情况下,您不会返回对象,而只是返回对象的地址,因此它不会导致复制构造函数调用。
如果您返回对象,这取决于编译器。
现代编译器足够聪明,可以通过使用返回值优化(RVO)和命名返回值优化(NRVO)来防止对复制构造函数的额外调用。
不,不会。
如果您只是
删除
a
,那么您的代码将导致内存泄漏,因为您仍然没有释放分配给a1
的内存。两者都已分别显式分配动态内存,因此必须分别释放两者。No.
In your case you are not returning an object but just address of an object so it does not result in copy constructor call.
In case when you are returning Objects, It depends on the compiler.
Modern day compilers are smart enough to prevent the additional call to copy constructor by using Return Value Optimization(RVO) and Named Return Value Optimization(NRVO).
No it won't.
If you just
delete
a
then your code will result in memory leak, because you still did not deallocate memory allocated toa1
. Both have been explicitly allocated dynamic memory separately, So both must be deallocated separately.