Deny std::vector from deleting its data

后端 未结 9 909
天涯浪人
天涯浪人 2021-01-17 11:03

I have the following case:

T* get_somthing(){
    std::vector vec; //T is trivally-copyable
    //fill vec
    T* temp = new T[vec.size()];
    memc         


        
9条回答
  •  梦毁少年i
    2021-01-17 11:38

    If there is an option to use smart pointers I would recommend std::shared_ptr with alias:

    template
    std::shared_ptr get_somthing(){
        using Vector = std::vector;
        using ReturnT = std::shared_ptr;
        std::vector* vec = new std::vector;
        //fill vec
        std::shared_ptr vectorPtr(vec); // (1)
        std::shared_ptr aliasedPtr(vectorPtr, vec->data()); // (2)
        return aliasedPtr;
    }
    

    (1) will create a shared pointer to the vector to be aliased to (2) creates a shared pointer that will destroy the aliased shared_ptr instead of removing contained data

提交回复
热议问题