当函数返回指向类的指针时,是否会调用复制构造函数?

发布于 2024-12-17 05:22:18 字数 312 浏览 0 评论 0原文

这个问题可能很愚蠢,但我想知道,当函数返回指向对象的指针时是否调用复制构造函数? 另外,考虑以下内容:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

后知后觉 2024-12-24 05:22:18

不,它不会调用复制构造函数,因为您返回的是对象的地址,而不是对象本身。

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 the GetPoineter function. a1 is untouched since it points to a completely different object.

山人契 2024-12-24 05:22:18

A* a = a1.GetPointer(); 也会调用复制构造函数吗?

编号
在您的情况下,您不会返回对象,而只是返回对象的地址,因此它不会导致复制构造函数调用。
如果您返回对象,这取决于编译器。
现代编译器足够聪明,可以通过使用返回值优化(RVO)命名返回值优化(NRVO)来防止对复制构造函数的额外调用。

另外我删除了,它会同时删除a1指向的地址吗?

不,不会。
如果您只是删除 a,那么您的代码将导致内存泄漏,因为您仍然没有释放分配给a1的内存。两者都已分别显式分配动态内存,因此必须分别释放两者。

so does A* a = a1.GetPointer(); calls copy constructor?

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).

Also i I delete a, will it delete the address pointed by a1 also?

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 to a1. Both have been explicitly allocated dynamic memory separately, So both must be deallocated separately.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文