0

I have a class Test which contains one member variable vector<MyCls> m_vObj and two member functions clear_vec and func. Please see the following code.

The func has a for loop, and each time it will push_back some instances into m_vObj, do some computation, and output the computation results. After that, I call clear_vec to clear the m_vObj vector, and prepare for the next loop.

Currently, I swap the m_vObj with an empty vector according to this suggestion. But I find the member function clear_vec is time-consuming especially for the swap(line 1).

As far as I understand, I just need to clear all elements in m_vObj and I do not need to free the memory. However, clear_vec in the for loop will frequently allocate memory and free memory. If I comment line 1 and just keep line 2, I can clear the vector but do not re-allocate memory frequently. Is it safe and will it be more efficient?

class Test {
private:
    vector<MyCls> m_vObj;

public:
    void clear_vec() {
        vector<MyCls>().swap(m_vObj); // line 1
        m_vObj.clear(); // line 2
    }

    void func() {
        for (int i = 0; i < 100; ++i) {

            // push_back some instances into m_vObj
            // do some computations with m_vObj
            // output computation results

            clear_vec();
        }
    }
};
user1024
  • 982
  • 4
  • 13
  • 26
  • `line 2` is redundant with `line 1`. `m_vObj` is already empty because you swapped it with a default constructed (empty) vector. – François Andrieux Oct 08 '19 at 14:22
  • 1
    `clear()` leaves the capacity (i.e. the allocated memory) unchanged. – Max Langhof Oct 08 '19 at 14:23
  • I believe the dupe should answer your question. If not, please clarify why `clear()` does not fulfill your goal and ping me so I can reopen. – Max Langhof Oct 08 '19 at 14:25
  • The swap trick is to free-up the memory. You dont need to do that so it's not the trick for you. Clear will empty the vector so it does what you need and is "safe". It doesnt free the memory so it should be faster than a version that does have to allocate memory each time round the loop - (especially if it has to allocate more than once due to the vector out-growing its exsiting capacity). – ROX Oct 08 '19 at 15:27
  • @MaxLanghof Thank you. I read many related questions including the one you mentioned, but all of them are talking about how to completely free the memory of vector. That's not what I want. I want to clear the elements in vector and in the same time not to free the memory, as I need to reuse the memory for the next loop. So, I want to ask is it safe and enough to only use `clear` and no need to use the `swap`. – user1024 Oct 09 '19 at 01:42
  • @ROX Thank you. Your answer reassures me. I also think I do not need the `swap` trick, as I do not want to free and re-allocate the memory. – user1024 Oct 09 '19 at 01:44

0 Answers0