所以有很多情况下,它需要在性能敏感的应用程序,我终于在打破骆驼的秸秆背部。它需要在C++ 98中编译,因为我们至少有一个平台只能保证C++ 98的合规性。std :: vector <>派生与resize(),不初始化原语和转发construct_back
编辑希望能够更清楚我想要什么。
实施例:
// This will allocate storage for 1024, and then loop 1024 times touching all of it just to place a 0 in it
std::vector<char> buffer(1024);
// Now read will write into that buffer, overwriting the 0s (we payed for the fill unnecessarily)
buffer.resize(read(someSource, &buffer[0], buffer.size()));
这是常见的C接口,几乎所有的C库用于写入数据到缓冲器。处理包含基元的缓冲区时,会出现同样的问题。新调整大小反而会是这个样子:
// Disabled for anything which doesn't pass boost::is_POD<T>, they get the standard version
void resize(size_t a_NewSize)
{
reserve(a_NewSize);
_end = _begin + a_NewSize;
}
construct_back将是一个转发的构造,1个const的参数看起来会像这样(未经):
template< typename T1 >
void construct_back(const T1& a_Arg1)
{
if(capacity() <= size()) // No room
reserve(size() + 1);
// Construct in place using Ts constructor that accepts const T1&
new (&(*end()) T(T1);
++_end; // Account for new element
}
construct_back就必须有所有参数^ 2重载的可能数量,这是在C++ 98中完美转发的常见强力方法。
它是你可以问的最简单的方法吗? – 2012-03-07 09:04:50
@Ylisar我听到你的伴侣,似乎没有人理解你的问题。我引用这个http://stackoverflow.com/questions/1461276/stdvector-reserve-and-push-back-is-faster-than-resize-and-array-index-w,希望能让其他人更清楚。 – dcousens 2012-03-09 02:55:45