Deny std::vector from deleting its data

后端 未结 9 907
天涯浪人
天涯浪人 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:59

    The first thing you should do is to get up, go to the one responsible for this design and (verbally in a professional manner) punch him/her in the face: It's a mess.

    Then, there's a way in C++11 to have a std::vector with automatic storage duration and have it not call its destructor:

    Put the std::vector into an union

    Like so:

    template
    union Ugly {
      std::vector vec;
      Ugly() {
        new (&vec) std::vector(); // Construct
      }
      ~Ugly() {
       // Don't destruct
      }
    };
    
    T* get_something(){
      Ugly mess;
      //fill mess.vec
      return mess.vec.data();
    }
    

    I'm not 100% sure whether this still counts as valid C++11, but it should "work". Now excuse me, I need to wash my hands to get rid of the crying feeling of shame for this code ...

    Oh, and one more thing: How do you intend to release the memory that the std::vector had allocated? You know, you can't (reliably) use the pointer returned by the member function data() for that!

提交回复
热议问题