小字符串优化(调试与发布模式)
Small String Optimisation (Debug vs Release mode)
我一直在使用此示例脚本检查小字符串优化(在 MSVC 2019 中(:
#include <string>
void* operator new(size_t size)
{
std::printf("global op new called, size = %zun", size);
void* ptr = std::malloc(size);
if (ptr)
return ptr;
else
throw std::bad_alloc{};
}
int main()
{
std::string test = "small value";
return 0;
}
注意,我从 https://en.cppreference.com/w/cpp/memory/new/operator_new 那里拿了void* operator new(size_t size)
。
在发布模式下,优化按预期工作(即new
不会被调用(,但在调试模式下,脚本实际上打印global op new called, size = 16
.向下钻取后,这似乎是由于标头xmemory
中的此代码段:
#if _ITERATOR_DEBUG_LEVEL == 0
#define _GET_PROXY_ALLOCATOR(_Alty, _Al) _Fake_allocator()
template <class _Alloc>
using _Container_proxy_ptr = _Fake_proxy_ptr_impl;
#else // _ITERATOR_DEBUG_LEVEL == 0
#define _GET_PROXY_ALLOCATOR(_Alty, _Al) static_cast<_Rebind_alloc_t<_Alty, _Container_proxy>>(_Al)
template <class _Alloc>
using _Container_proxy_ptr = _Container_proxy_ptr12<_Rebind_alloc_t<_Alloc, _Container_proxy>>;
#endif // _ITERATOR_DEBUG_LEVEL == 0
我们可以看到,在发布模式下(即_ITERATOR_DEBUG_LEVEL == 0
( 我们使用_Fake_proxy_ptr_impl
,而在调试模式下我们使用使用new
的_Container_proxy_ptr12
。
我的问题很简单:为什么调试模式和发布模式之间存在这种差异?
小字符串优化在调试模式下仍然存在。 如果我们创建一个更大的string
std::string test = "large value.large value.large value.large value.";
然后我们得到实际的string
分配
global op new called, size = 64
在调试和发布版本中。
您观察到的是用于迭代器调试的容器代理的分配(从#if _ITERATOR_DEBUG_LEVEL
可以看出(
struct _Container_proxy { // store head of iterator chain and back pointer
您可以通过使用/D _ITERATOR_DEBUG_LEVEL=0
构建来禁用迭代器调试(但随后它将对所有容器禁用,因此对于vector
、map
等也是如此(。
相关文章:
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- c++方法参数只能在linux的发布模式下自行更改
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 在C++的一系列数字中查找重复模式
- 是否允许使用带有"w+"模式的 freopen 进行标准设置?
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 插入队列的模式模式
- 显示未处于模式模式的对话框窗体