Vargas
Vargas

Reputation: 2155

Use std::vector to construct a object and use it

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.

Upvotes: 1

Views: 318

Answers (4)

MSalters
MSalters

Reputation: 179789

Almost there:

vector<MyClass> MyVec;
MyVec.push_back(MyClass()); // Any decent compiler will inline this, eliminating temporaries.
MyClass &item = MyVec.back();

Upvotes: 1

Mark B
Mark B

Reputation: 96241

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?

Upvotes: 0

BЈовић
BЈовић

Reputation: 64223

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

Upvotes: 3

Steve Townsend
Steve Townsend

Reputation: 54138

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.

Upvotes: 3

Related Questions