使用'new'时,通过引用返回指针和通过指针本身返回指针有什么区别?

When use 'new', what's the difference between returning the pointer by reference or by pointer itself?

在c++中,当我在函数中使用"new"时,会创建一个指针。 那么,当我考虑return函数的结果时,by reference和by pointer有什么区别?

喜欢:

参考

Sample& (int & x, int & y){
    Sample * temp = new Sample(x,y);
    return *temp;
}

BY 指针本身

Sample* (int & x, int & y){
    Sample * temp = new Sample(x,y);
    return temp;
}

好像是'new'使用不当会导致内存泄漏,请问以上这些情况会发生内存泄漏吗?或者以后再利用这些return材料会有什么风险?

如果您 return 一个引用,它向调用者暗示他们不需要 delete returned 对象,从而导致内存泄漏。如果他们只查看您的 API 而不是函数实现,则含义会更强烈。

推荐使用智能指针让调用者知道对象是动态分配的,他们应该在生命周期管理中合作。如果没有其他令人信服的理由,按值 返回 会更好。