智能指针与数组

来源:互联网 发布:淘宝闪电退款 编辑:程序博客网 时间:2024/05/20 07:34

有的时候需要由local函数在heap中alloc 一个数组空间并返回给外部使用。例如在windows编程中常常需要转换编码,

转换编码返回值常常是alloc 在heap中如果例如返回一个char *. 如果外部在使用完以后不做删除操作就容易造成内存泄漏。

本质上char* 在heap中是一个char[] 。可以将返回值存在智能指针中,来自动销毁(shared_ptr, unique_ptr)


C++11智能指针处理Array对象


//C++11的<memory>中有一整套智能指针,//完全可以避免写手动的delete代码,//但是它默认使用delete删除对象,//如果是数组对象,需要指定自定义的删除方法,支持delete[]std::shared_ptr<int> p(new int[10],    [](int* p){        delete[] p;    });//或者使用helperstd::shared_ptr<int> p(new int[10],std::default_delete<int[]>()); 

unique_ptr跟shared_ptr不一样,它直接支持持有数组对象


std::unique_ptr<int[]> p(new int[10]);//okstd::shared_ptr<int[]> p(new int[10]);//error, does not compilestd::unique_ptr<int, void(*)(int*)> p(new int[10],    [](int* p){        delete[] p;    });

一个智能指针自动删除对象数组的例子

#include <iostream>#include <memory>class myData{public:    myData():num(new int)    {    }    void setValue(const int n)    {        *num = n;    }    int getValue() const    {        return *num;    }    ~myData()    {        std::cout<<"Call the destructor to delete the data"<<*num<<std::endl;        if(num){            delete num;            num = NULL;        }    }private:    int * num;};class data{public:private:    int * p_data;};myData* allocNum(){    myData* num = new myData[10];    for(unsigned i = 0; i<10; ++i)        num[i].setValue(i);    return num;}void test_func(){    std::unique_ptr<myData[]> ptr (allocNum());    for(unsigned i = 0; i<10; ++i)        std::cout<<static_cast<myData*>(ptr.get())[i].getValue()<<" ";    std::cout<<std::endl;}int main(){    test_func();    return 0;}


0 0