为什么sizeof(std :: string)只有8个字节? [英] Why is sizeof(std::string) only eight bytes?
问题描述
为什么 std :: string
的大小取决于 sizeof(std :: string)
yield 8 ?
我认为应该超过 8
int (
sizeof(int)== 8
在我的机器上)data成员给予 std :: string :: length()
和 std :: string :: size()
std: :string
未由C ++标准指定。它只描述类的行为。但是,我希望在类中有多个指针的信息价值。特别是:
- 指向实际字符串的指针。
- 使用的实际大小。
位置,因此占用与 char *
[在大多数架构]中完全相同的空间量。
事实上,看看我的Linux机器附带的C ++头文件,当你看看(其中,根据注释,是pre-C ++ 11,但是我认为这两种方法都有代表性):
size_type
length()const _GLIBCXX_NOEXCEPT
{return _M_rep() - > _M_length; }
,然后按照:
_Rep *
_M_rep()const _GLIBCXX_NOEXCEPT
{return&((reinterpret_cast< _Rep *>(_M_data()))[ - 1] }
这又导致:
_CharT *
_M_data()const _GLIBCXX_NOEXCEPT
{return _M_dataplus._M_p; }
这导致
//数据成员(私人):
mutable _Alloc_hider _M_dataplus;
,然后我们进入:
struct _Alloc_hider:_Alloc
{
_Alloc_hider(_CharT * __dat,const _Alloc& __a)_GLIBCXX_NOEXCEPT
:_Alloc(__a),_M_p
_CharT * _M_p; //实际数据。
};
字符串的实际数据为:
struct _Rep_base
{
size_type _M_length;
size_type _M_capacity;
_Atomic_word _M_refcount;
};
所以,这是一个简单的指针 _M_p
隐藏在几层吸气剂和一点铸造...
Why is std::string
's size, as determined by sizeof(std::string)
, yield 8
?
I thought it should be more than 8
as it has to have an int
(sizeof(int) == 8
on my machine) data member for giving std::string::length()
and std::string::size()
in O(1) and probably a char*
for characters.
The implementation of std::string
is not specified by the C++ standard. It only describes the classes behaviour. However, I would expect there to be more than one pointer's worth of information in the class. In particular:
- A pointer to the actual string.
- The size available.
- The actual size used.
It MAY of course store all these in a dynamically allocated location, and thus take up exactly the same amount of space as char*
[in most architectures].
In fact looking at the C++ header that comes with my Linux machine, the implementation is quite clear when you look at (which, as per comments, is "pre-C++11", but I think roughly representative either way):
size_type
length() const _GLIBCXX_NOEXCEPT
{ return _M_rep()->_M_length; }
and then follow that to:
_Rep*
_M_rep() const _GLIBCXX_NOEXCEPT
{ return &((reinterpret_cast<_Rep*> (_M_data()))[-1]); }
which in turn leads to:
_CharT*
_M_data() const _GLIBCXX_NOEXCEPT
{ return _M_dataplus._M_p; }
Which leads to
// Data Members (private):
mutable _Alloc_hider _M_dataplus;
and then we get to:
struct _Alloc_hider : _Alloc
{
_Alloc_hider(_CharT* __dat, const _Alloc& __a) _GLIBCXX_NOEXCEPT
: _Alloc(__a), _M_p(__dat) { }
_CharT* _M_p; // The actual data.
};
The actual data about the string is:
struct _Rep_base
{
size_type _M_length;
size_type _M_capacity;
_Atomic_word _M_refcount;
};
So, it's all a simple pointer called _M_p
hidden inside several layers of getters and a bit of casting...
这篇关于为什么sizeof(std :: string)只有8个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!