1

I need to avoid the additional cost of copying and destructing the object contained by a std::vector caused by this answer.

Right now I'm using it as a std::vector of pointers, but I can't call std::vector::clear() without deleting each object before nor I can use std::auto_ptr with std containers.

I wanted to do something like this:

vector<MyClass> MyVec;
MyVec.push_back();
MyClass &item = MyVec.back();

This would create a new object with the default constructor and then I could get a reference and work with it.

Any ideas on this direction?

RESOLVED: I used @MSalters answer with @Moo-Juices suggestion to use C++0x rvalue references to take vantage of std::move semantics. Based on this article.

Community
  • 1
  • 1
Vargas
  • 2,125
  • 2
  • 33
  • 53

4 Answers4

3

Boost.PointerContainer classes will manage the memory for you. See especially ptr_vector.

With the container boost::ptr_vector<T> you can use push_back(new T);, and the memory for T elements will get freed when the container goes out of scope.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • 1
    Although as we had yesterday, beware that `push_back(new T);` offers no exception guarantee - it can create the T and then throw, leaking the object (http://stackoverflow.com/questions/4185350/is-it-safe-to-push-back-dynamically-allocated-object-to-vector/4185460). However, as Steve himself said yesterday, if the rest of your program/OS isn't robust, then there may be no need for this one line to be any better. – Steve Jessop Nov 16 '10 at 14:05
3

Instead of storing objects, store shared_ptr. This will avoid object copying, and will automatically destruct the object when removed from the vector.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • 1
    Or `unique_ptr`, which is much cheaper if you know the vector will own the objects pointed to. – rubenvb Nov 16 '10 at 16:57
1

Almost there:

vector<MyClass> MyVec;
MyVec.push_back(MyClass()); // Any decent compiler will inline this, eliminating temporaries.
MyClass &item = MyVec.back();
MSalters
  • 173,980
  • 10
  • 155
  • 350
  • I've resolved using this AND using C++0x std::move semantics (according to this: http://msdn.microsoft.com/en-us/library/dd293665.aspx) – Vargas Nov 17 '10 at 11:51
0

You can do this with resize, which will default construct any additional objects it has to add to the vector:

vector MyVec;
MyVec.resize(MyVec.size() + 1);
MyClass &item = MyVec.back();

But do consider why you need to do this. Has profiling really shown that it's too expensive to copy the objects around? Are they non-copyable?

Mark B
  • 95,107
  • 10
  • 109
  • 188