为什么 std::string 上的 Sizeof 运算符会产生意外结果?
Why does Sizeof operator on a std::string yield unexpected result?
在下面的代码中:
#include <iostream>
#include <string>
using namespace std;
int main() {
char buff[100];
_snprintf(buff, sizeof(buff), "%s %d", "Name",2); //snprintf incase of ideone
string buffAsStdStr = buff;
cout<<buffAsStdStr<<endl;
cout<<"len: "<<buffAsStdStr.length()<<endl;
cout<<sizeof(buffAsStdStr)<<endl;
return 0;
}
buffAsStdStr 中的字符串长度为 6,但 sizeof 显示的值在 运行 in Visual Studio 2012 和 ideone 中为 32 时为 28。
预期大小为 7,包括尾随 NULL 字符。
sizeof 运算符出现这种意外结果的原因是什么?
为什么结果在 visual studio 和 ideone 之间发生变化?
你应该使用 std::string::size
, or std::string::length
.
sizeof
returns 对象的大小,不是包含的字符数。
std::string
实例的 sizeof
只是 returns std::string
的 "internal representation" 的大小(以字节为单位),即您可以想到它就像每个 std::string
数据成员的 sizeof
的总和(也可能涉及填充)。
例如,在使用 VS2015 的 32 位调试版本中,sizeof(std::string)
returns 28;在 64 位调试版本中,我得到 40;在 32 位版本中我得到 24,在 64 位版本中我得到 32。
这是因为 std::string
的 内部 表示随着不同的构建选项发生变化 :例如调试版本通常包含额外的机制来帮助发现错误,这会增加表示的大小;此外,在 64 位构建中,指针更大,因此相对于 32 位构建等,大小再次增加。
因此,您从 std::string
实例上调用的 sizeof
获得的数字通常与 char
的数字 不同使字符串的文本。要获得此号码,您必须致电 std::string::size
or std::string::length
.
原因是 sizeof(buffAsStdStr)
不是字符串的长度,而是 std::string
实例的大小,并且给定类型的每个实例都具有相同的大小。
sizeof
的结果是编译时决定的,如果你有一个T
类型的对象o
,sizeof(o)
和sizeof(T)
是等价的.
此外,不需要 std::string
来存储尾随的空字符,并且可以包含 "non-terminating" 个空字符。
在下面的代码中:
#include <iostream>
#include <string>
using namespace std;
int main() {
char buff[100];
_snprintf(buff, sizeof(buff), "%s %d", "Name",2); //snprintf incase of ideone
string buffAsStdStr = buff;
cout<<buffAsStdStr<<endl;
cout<<"len: "<<buffAsStdStr.length()<<endl;
cout<<sizeof(buffAsStdStr)<<endl;
return 0;
}
buffAsStdStr 中的字符串长度为 6,但 sizeof 显示的值在 运行 in Visual Studio 2012 和 ideone 中为 32 时为 28。 预期大小为 7,包括尾随 NULL 字符。
sizeof 运算符出现这种意外结果的原因是什么? 为什么结果在 visual studio 和 ideone 之间发生变化?
你应该使用 std::string::size
, or std::string::length
.
sizeof
returns 对象的大小,不是包含的字符数。
std::string
实例的 sizeof
只是 returns std::string
的 "internal representation" 的大小(以字节为单位),即您可以想到它就像每个 std::string
数据成员的 sizeof
的总和(也可能涉及填充)。
例如,在使用 VS2015 的 32 位调试版本中,sizeof(std::string)
returns 28;在 64 位调试版本中,我得到 40;在 32 位版本中我得到 24,在 64 位版本中我得到 32。
这是因为 std::string
的 内部 表示随着不同的构建选项发生变化 :例如调试版本通常包含额外的机制来帮助发现错误,这会增加表示的大小;此外,在 64 位构建中,指针更大,因此相对于 32 位构建等,大小再次增加。
因此,您从 std::string
实例上调用的 sizeof
获得的数字通常与 char
的数字 不同使字符串的文本。要获得此号码,您必须致电 std::string::size
or std::string::length
.
原因是 sizeof(buffAsStdStr)
不是字符串的长度,而是 std::string
实例的大小,并且给定类型的每个实例都具有相同的大小。
sizeof
的结果是编译时决定的,如果你有一个T
类型的对象o
,sizeof(o)
和sizeof(T)
是等价的.
此外,不需要 std::string
来存储尾随的空字符,并且可以包含 "non-terminating" 个空字符。