如何在C++中确定标准库字符串或其他非基本数据类型在内存中的大小
How to determine the size in memory of a standard library string or other non-fundamental datatype in C++?
如何确定非基本C++类型(如字符串、向量、多映射等)的内存大小?
我知道我可以使用sizeof:获得理论上的"起始"尺寸
string test = "thisisatest"; // sizeof returns 28
string test2 = "thisisareallylongtestdearlordthisstringisclearlymorethan28bytesandisarunonsentenceaintnobodygonnabreakamystride"; // sizeof returns 28
但是,我如何才能看到test2(而不是字符串类型)使用了多少字节内存呢?
您必须知道您使用的类是如何实现的。sizeof(obj)
只返回对象本身的内存大小,而不返回堆上已分配数据的内存使用情况。std::string为字符串本身的数据分配内存。实现是自由的,可以实现任何形式的。也许std::string只为一个字节分配1k内存,以便更快地进行进一步的操作。
获得实际所需内存总量的唯一方法是查看所使用的实现内部,并将所有分配的内存和类本身的大小相加。
在C++11中,您可以利用分配器可以具有状态这一事实。此解决方案与实现无关。
template<class T>
struct myalloc : std::allocator<T>
{
using pointer = typename std::allocator<T>::pointer;
using const_pointer = typename std::allocator<T>::const_pointer;
using size_type = typename std::allocator<T>::size_type;
pointer allocate( size_type n, std::allocator<void>::const_pointer hint = 0 )
{
if (counter)
(*counter)+= sizeof(T)*n;
return std::allocator<T>::allocate( n, hint );
}
void deallocate( pointer p, size_type n )
{
if (counter)
(*counter)-= sizeof(T)*n;
return std::allocator<T>::deallocate( p, n );
}
template< class U > struct rebind { typedef myalloc<U> other; };
typedef std::true_type propagate_on_container_copy_assignment;
typedef std::true_type propagate_on_container_move_assignment;
typedef std::true_type propagate_on_container_swap;
myalloc( int * p = 0 ) : counter(p) {}
int * counter;
};
typedef std::basic_string< char, std::char_traits<char>, myalloc<char> > mystring;
你可以这样使用它:
int main()
{
int cnt = sizeof( mystring );
mystring c ("hello, world!", custom_alloc<char>(&cnt) );
cout << cnt << endl; // result is implementation dependent
return 0;
}
相关文章:
- 防止主数据类型C++的隐式转换
- 哪些 C++ 数据类型是 Metal 和所有其他 C++ 平台共有的
- 只知道运行时的数据类型.如何将数据详细信息隐藏到使用它们的其他类
- 如何将模运算符与其他数据类型一起使用
- 将多种数据类型写入文件时的其他行和额外的数组元素
- 是否要确保一个线程修改的任何数据类型的共享变量对其他线程可见
- 如何仅接受整数并忽略其他数据类型
- 编译器是否有可能检测整数溢出或其他数据类型溢出的可能性
- 是否有可能在c++中为向量(或其他类似的数据类型)编写用户迭代类
- 具有其他类数据类型的C++构造函数
- Streamsize,Streamoff和其他与流相关的数据类型的实际类型是什么
- 其他类数据类型的扩展boost::lexical_cast
- 如何正确地将std::函数用于其他数据类型(在优先级队列中)
- 您可以将C++桌面应用程序中的输入数据或其他类型的数据存储在文本文件之外的文件中吗
- GCC编译器是否可以处理比long / long / int更大的其他数据类型?
- 是否可以在VTK中使用(polyData)编写器来处理来自其他库的数据类型?
- 将curl结果中的字节组解释为其他数据类型的方法
- 在C/ c++或任何其他类似语言中,对变量或数据类型应用&符号时返回的地址类型
- 为什么指向 char 的指针与其他数据类型的指针相比行为不同
- 如何在C++中确定标准库字符串或其他非基本数据类型在内存中的大小