简体   繁体   English

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

[英]passing new object to function c++

I just want to know if this is a bad practice to do. 我只是想知道这是不好的做法。

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

The new car() object should live after calling it from happyFunction and later it should be destroyed . 新的car()对象应该在从happyFunction调用后happyFunction ,之后它应该被销毁。 Now is that ok to do. 现在可以了。 I mean shouldn't I delete the memory allocated for that instance? 我的意思是我不应该删除为该实例分配的内存?

Example to make it more clear. 示例使其更清晰。

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

Is this a good practice to do? 这是一个很好的做法吗? Should I delete the memory allocation? 我应该删除内存分配吗? I hope my question is clear. 我希望我的问题很明确。 thank you. 谢谢。

happyFunction(new Car()); 

It's not bad practice in itsself (although almost certainly is wrong), the memory could be deleted inside the function. 它本身的做法并不坏(虽然几乎肯定是错的),内存可以在函数内删除。 But that would be confusing so it's really not the best idea. 但那会让人感到困惑,所以这真的不是最好的主意。

Also although it's safe with one parameter, if it was like this 虽然它只有一个参数是安全的,如果是这样的话

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

And one of the news threw an exception after the other new executed, the would be no way to free the memory so it's not safe. 其中一个新闻在另一个新执行后抛出异常,将无法释放内存,因此它不安全。

You always have to free memory yourself in c++ so your second example leads to a big memory leak. 你总是要用c ++自己释放内存,所以你的第二个例子会导致大量的内存泄漏。 There are classes such as unique_ptr and shared_ptr to help you manage it without having to write a delete yourself, you can find any number of tutorials online about them 有一些类如unique_ptr和shared_ptr可以帮助你管理它而不必自己编写删除,你可以在网上找到任意数量的教程

There are two possibilities: 有两种可能性:

  1. happyFunction is supposed to take ownership of the pointer, and the caller never worries about it. happyFunction应该取得指针的所有权,而调用者从不担心它。 In this case, it would be more sensible to write 在这种情况下,写作会更明智

     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 is only supposed to use the pointer: the caller retains control and ownership. happyFunction只能使用指针:调用者保留控制权和所有权。 In this case, it would be better to pass a reference so there is no suggestion that ownership is transferred 在这种情况下,最好传递一个引用,这样就不会建议转移所有权

     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 } 

Caller can retain ownership of the pointer to new Car() if your happyFunction() returns pointer to that memory created by new Car() . 如果您的happyFunction()返回指向由new Car()创建的内存的指针,则调用者可以保留指向new Car()的指针的所有权。

Consider following code: 考虑以下代码:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM