将新对象传递给函数 C++

passing new object to function c++

本文关键字:函数 C++ 新对象 对象      更新时间:2023-10-16

我只想知道这是否是一种不好的做法。

for(int i=0;i<1000;i++)
    happyFunction(new Car());

新的car()对象应该在从happyFunction调用它后存活,稍后它应该被销毁。现在就可以了。我的意思是我不应该删除为该实例分配的内存吗?

示例使其更清楚。

int i = 0;
for (i=0;i<1000;i++){
    new car();
}

这是一个好的做法吗?我应该删除内存分配吗?我希望我的问题很清楚。谢谢。

happyFunction(new Car()); 

这本身并不是一个坏的做法(尽管几乎可以肯定是错误的),内存可以在函数中删除。但这会令人困惑,所以这真的不是最好的主意。

另外,尽管使用一个参数是安全的,但如果是这样的

happyFunction(new Car(), new Thing()); 

其中一个新闻在另一个新执行后抛出了一个异常,这将无法释放内存,所以它不安全。

你总是必须在 c++ 中自己释放内存,所以你的第二个示例会导致很大的内存泄漏。有一些类,例如 unique_ptr 和 shared_ptr 可以帮助您管理它,而无需自己编写删除,您可以在线找到有关它们的任意数量的教程

有两种可能性:

  1. happyFunction应该拥有指针的所有权,调用方从不担心它。在这种情况下,写会更明智

    void happyFunction(std::unique_ptr<Car> &&car)
    {
        // car is mine now, and is automatically destroyed when I return
        // unless I explicitly request otherwise
    }
    void caller()
    {
        happyFunction(std::unique_ptr<Car>(new Car));
        // the new Car is immediately handed over to the unique_ptr
        // and I don't have to worry about leaks
    }
    
  2. happyFunction只应该使用指针:调用方保留控制权和所有权。在这种情况下,最好传递一个引用,这样就不会建议所有权转移

    void happyFunction(Car &car)
    {
        // car is still owned by the caller,
        // I just get a reference to use in here
    }
    void automatic_caller()
    {
        Car car;
        happyFunction(car);
        // car is always owned by me, and is
        // automatically destroyed at the end of this scope
    }
    // alternatively (only if car should live longer than the enclosing scope)
    void dynamic_caller()
    {
        std::unique_ptr<Car> car(new Car);
        // or get pointer from somewhere else ...
        // or get shared_pointer, etc. etc.
        happyFunction(*car);
        // again car is destroyed here unless we do something special
    }
    
如果您的

happyFunction()返回指向new Car()创建的内存的指针,则调用方可以保留指向new Car()的指针的所有权。

请考虑以下代码:

#include <string>
#include <iostream>
using std::string;
using std::cout;
class Car
{
public:
    string s;
    Car(string str):s(str) {}
};
Car* happyFunction(Car *pCar)
{
    // do something with data pointed to by pCar
    return pCar;
};
int main()
{
    // outer pointer to memory allocated by new operator
    Car *pCar = happyFunction(new Car("test"));
    // pCar still points to valid object even after happyFunction() content
    // went out of scope
    cout << pCar->s << "n";
    // release pCar memory outside the happyFunction()
    delete pCar;
    return 0;
}