开发者

Do I pay for default construction here and if so can I avoid it

In the case where T is expensive to construct I'd like to know if I pay for default construction in the following case (I think I do)

std::function< T() > make_t;
std::vector< T > t( 100000 );
std::generate( t.begin(), t.end(), make_T );

If I do have to pay for it can I avoid it? I wanted to write something like

std::function< T() > make_t;
std::vector< T > t;
t.reserve( 100000 );
std::generate( t.begin(), t.end(), make_T );

But that does not work because it does not move t.end() to the end of what is reserved. Is the following safe/advisable/correct?

std::function< T() > make_t;
std::vector< T > t;
t.reserve( 100000 );
std::generate( t.begin(), t.begin() + 100000, make_T );

I also thought I might be able to use a back_inserter but the interface is right for what I have (I have a function that generates a new T object every time it is acc开发者_开发知识库essed not a pair of iterators to a range).

C++0x solutions preferred to C++03 solutions (i.e., ones that leverage the new standard if there's a better way to do it there) preferred to solution that need to use boost.


std::function< T() > make_t;
std::vector< T > t;
int const count = 100000;
t.reserve( count );
std::generate_n( std::back_inserter(t), count, make_T );

std::back_inserter is in <iterator>.


You can fix your second solution with the use of the std::back_inserter iterator, which does the push_back for you:

std::vector< T > t;
t.reserve(100000);
std::generate_n(std::back_inserter(t), 100000, make_t);


You will pay for default construction in the case you were afraid of. You should prove it to yourself by inspecting the generated assembly code on your particular platform, though.

I'd make the vector hold shared_ptr<T> rather than plain T, then the rest is easy. It also facilitates moving the objects around later if you turn out to need that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜