将新对象传递给函数 C++
passing new object to function c++
我只想知道这是否是一种不好的做法。
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 可以帮助您管理它,而无需自己编写删除,您可以在线找到有关它们的任意数量的教程
有两种可能性:
-
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 }
-
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;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 如何获取std::result_of函数的返回类型
- 如何在c++中为模板函数实例创建快捷方式
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗