简体   繁体   中英

C++: why boost::ptr_vector resize needs object to have default constructor

I am using a boost::ptr_vector over just std::vector as it will handle the deletion of all of the pointers for me. However when I do:

ptr_vector<SoftLabelRandomTreeFunctor> functors;
functors.resize(number_of_functors);

It complains that SoftLabelRandomTreeFunctor does not have a default constructor. However, I was under the impression that it would just need to resize big enough to fit number_of_functors * the size of a pointer to a SoftLabelRandomTreeFunctor , not number_of_functors * the size of a SoftLabelRandomTreeFunctor itself?

I am not really experienced with Boost, so take my answer with a grain of salt. However, skimming through the docs for boost::ptr_vector made me think that what you want (as follows from the comments to the question) should be possible to do this way:

boost::ptr_vector< boost::nullable<SoftLabelRandomTreeFunctor> > functors;
functors.resize(number_of_functors, 0);

The references for you to read and make your own conclusion:

When you write functors.resize(number_of_functors) you potentially increase the size of the vector to contain number_of_functors elements inside. Since ptr_vector by default disallows storing NULL values, it needs to put a meaningfull data into the inflated array. The function intends to call new SoftLabelRandomTreeFunctor() for every new element and it requires a default constructor for that.

If you want to allow NULLs, you need the boost::nullable as suggested by Alexey Kukanov answer, and as in the tutorial included in the manual ( (here) ).

However, if you just intend to reserve enough memory for number_of_functors elements without semantically creating them and without increasing the array size --- you don't need nullable and you should call instead:

functors.reserve(number_of_functors)

Note that after this, you still need to increase the array size when you put new elements (eg via push_back ). You will have a guarantee though that push_back won't call a memory reallocation as long as your size doesn't exceed number_of_functors .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM