Deny std::vector from deleting its data

后端 未结 9 903
天涯浪人
天涯浪人 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条回答
  •  执笔经年
    2021-01-17 11:36

    I don't know if you will like this very hacky solution, I definitely would not use it in production code, but please consider:

    #include 
    using namespace std;
    
    #include 
    
    template
    T* get_somthing(){
        std::vector vec = {1,2,3}; //T is trivally-copyable
    
        static std::vector static_vector = std::move(vec);
    
        return static_vector.data();
    }  
    
    int main() {
        int * is = get_somthing();
        std::cout << is[0] << " " << is[1] << " " << is[2];
        return 0;
    }
    

    so, as you can see inside the get_somthing I define a static vector, of same type as you need, and use std::move on it, and return it's data(). It achieves what you want, but this is dangerous code, so please use the good old fashioned copy the data again methodology and let's wait till N4359 gets into the mainstream compilers.

    Live demo at: http://ideone.com/3XaSME

提交回复
热议问题