关于函数外释放内存的问题,
byte *temp = new byte[10]
return temp;
我一个函数里返回一个指针,我要在函数外释放空间,这样很不安全,怎么样做好一点,谢谢各位高手
[解决办法]
可以用封装配对的方式,这样不容易漏掉:
byte* create(void)
{
byte *temp = new byte[10];
return temp;
}
void destory(byte* p)
{
delete[] p;
}
[解决办法]
函数外面控制内存
void fun(byte* tmp)
{
}
void main()
{
byte *temp = new byte[10];
fun(tmp);
delete[] temp;
}
[解决办法]
或者使用智能指针
[解决办法]
Do you realize that your code is totally C code? Also it's consider to be a bad design to allocate memory in one function and need to be released in another function. strdup is a notorious bad design sample.
If you want to write C++ code, just use vector?
[解决办法]
//C++11
std::shared_ptr<byte> CreateArray()
{
byte *temp = new byte[10];
return std::shared_ptr<byte>(temp,[](byte * ptr){delete [] ptr;});
}
w完美解决
[解决办法]
这就是STL的效率
智能指针+匿名函数定制删除器
用户只管用,不用管删除了
申请与释放代码在一起,函数用户负担也最轻。
[解决办法]
why don't you just return array? Any reasons to use pointer or smart pointer in this case?
std::array<int, 10> CreateArray()
{
return std::array<int, 10>();
}
[解决办法]
你说得对 配合move语义的使用 std::array<int,10〉是更好的解决方案
我还没有适应C++11返回容器的快感。还没有转换思维到C++11上来