开发者

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

开发者 https://www.devze.com 2023-01-25 03:16 出处:网络
I need to avoid the additional cost of copying and destructing the object contained by a std::vector caus开发者_StackOverflow中文版ed by this answer.

I need to avoid the additional cost of copying and destructing the object contained by a std::vector caus开发者_StackOverflow中文版ed 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.


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.


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


Almost there:

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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号