返回指针函数声明的数据 [英] return pointer to data declared in function
本文介绍了返回指针函数声明的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道这不会工作,因为变量x被破坏当函数返回时:
I know this won'T work because the variable x gets destroyed when the function returns:
int* myFunction()
{
int x = 4; return &x;
}
让我怎么正确地返回一个指向我的函数中创造的东西,和我有什么照顾有?如何避免内存泄漏?
so how do I correctly return a pointer to something I create within the function, and what do I have to take care with? How do I avoid memory leaks?
我也用的malloc:
I've also used malloc:
int* myFunction2()
{
int* x = (int*)malloc(sizeof int); *x = 4; return x;
}
你如何正确地做到这一点 - 在C和C ++
How do you correctly do this - in C and C++ ?
推荐答案
有关C ++中,你可以使用智能指针强制过户。 的auto_ptr
或的boost :: shared_ptr的
都是不错的选择。
For C++, you can use a smart pointer to enforce the ownership transfer. auto_ptr
or boost::shared_ptr
are good options.
这篇关于返回指针函数声明的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文