[英]C++ STL vector reserve
我已經使用以下代碼在stl向量上進行了測試:
struct structA{
char charArray[256];
}
structA a;
..assign 256 characters to a.charArray
vector<structA> v1;
v1.reserve(1000);
for(int i=0; i<1000; i++){
v1.push_back(a);
}
我意識到每16次push_back,v1.push_back就會出現峰值。 我懷疑存在重新分配的內存。 我想知道為什么會這樣,因為我已經使用了預備隊? 我試圖使用vectorv1(1000)聲明向量,它也給出了相同的行為。
順便說一下,如果我將char增加到512,它只需要8個push_back,8 * 512就會產生大約4k的內存。 這個問題會與內存分頁有關嗎?
謝謝。
運行這個簡單的測試,看看是否有任何你不想要或不想要的分配或解除分配。
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <algorithm>
template <class T> class my_allocator;
// specialize for void:
template <> class my_allocator<void> {
public:
typedef void* pointer;
typedef const void* const_pointer;
// reference to void members are impossible.
typedef void value_type;
template <class U> struct rebind { typedef my_allocator<U> other; };
};
template <typename T> class my_allocator : public std::allocator<T> {
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U>
struct rebind {
typedef my_allocator<U> other;
};
my_allocator() throw()
{
}
my_allocator(const my_allocator& to_copy) throw()
{
}
template <class U>
my_allocator(const my_allocator<U>& to_copy) throw()
{
}
~my_allocator() throw()
{
}
pointer address(reference x) const
{
return std::allocator<T>::address(x);
}
const_pointer address(const_reference x) const
{
return std::allocator<T>::address(x);
}
pointer allocate(size_type s1, typename std::allocator<void>::const_pointer hint = 0)
{
size_t block_size = s1 * sizeof (T);
std::cout << "allocated, bytes: " << block_size << "\n";
return std::allocator<T>::allocate(s1, hint);
}
void deallocate(pointer p, size_type n)
{
size_t block_size = n * sizeof (T);
std::cout << "deallocated, bytes: " << block_size << "\n";
std::allocator<T>::deallocate(p, n);
}
size_type max_size() const throw()
{
return std::allocator<T>::max_size();
}
void construct(pointer p, const T& val)
{
std::allocator<T>::construct(p, val);
}
void destroy(pointer p)
{
std::allocator<T>::destroy (p);
}
};
struct structA{
char charArray[256];
};
int main()
{
structA a;
std::cout << "Test 1, with reserve\n";
{
std::vector<structA, my_allocator<structA> > v1;
v1.reserve(1000);
for(int i=0; i<1000; i++){
v1.push_back(a);
}
}
std::cout << "Test 1, done\n";
std::cout << "Test 2, without reserve\n";
{
std::vector<structA, my_allocator<structA> > v1;
for(int i=0; i<1000; i++){
v1.push_back(a);
}
}
std::cout << "Test 2, done\n";
return 0;
}
你最好的選擇是啟動調試器並“進入”保留並看看那里發生了什么 - 也許你的STL實現對reserve()
沒有任何作用。 步入push_back()
也不會有任何傷害 - 這樣你就會確切地知道究竟是什么了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.