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

时间:2012-08-07 11:22:55

标签: c++

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

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

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

让它更清晰的例子。

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

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

3 个答案:

答案 0 :(得分:7)

happyFunction(new Car()); 

它本身的做法并不坏(虽然几乎肯定是错的),内存可以在函数内删除。但那会让人感到困惑,所以这真的不是最好的主意。

虽然使用一个参数是安全的,但如果它是这样的

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

其中一条新闻在另一条新执行后抛出异常,将无法释放内存,因此不安全。

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

答案 1 :(得分:2)

有两种可能性:

  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
    }
    

答案 2 :(得分:0)

如果您的new Car()返回指向happyFunction()创建的内存的指针,则调用方可以保留指向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;
}