首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >string为一个字符串分配内存2次

string为一个字符串分配内存2次
EN

Stack Overflow用户
提问于 2020-08-19 23:02:51
回答 1查看 335关注 0票数 5
代码语言:javascript
复制
#include <iostream>
#include <string>

void* operator new(size_t size) {
    std::cout << "Allocated: " << size << " Bytes\n";
    return malloc(size);
}

void operator delete(void* var) {
    std::cout << "Deleted\n";
    free(var);
}

int main() {
    std::string name0 = "Ahmed Zaki Marei";
    //std::string name1 = "Lara Mohammed";

    std::cout << name0 << "\n";
    //std::cout << name1 << "\n";
}

当我试图运行这段代码时,它提供了以下输出:

代码语言:javascript
复制
Allocated: 8 Bytes
Allocated: 32 Bytes
Ahmed Zaki Marei
Deleted
Deleted

为什么它先分配8个字节,然后再分配32个字节?有人能解释一下吗?( thx!)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-20 12:21:53

正如C.M.在评论中所指出的:这是MS在调试模式下的行为,与_ITERATOR_DEBUG_LEVEL有关。释放后一切都很好。

我很好奇,所以我自己测试了它,堆栈在new中的第一个断点上读取了这个

代码语言:javascript
复制
operator new(unsigned int size)
std::_Default_allocate_traits::_Allocate(const unsigned int _Bytes)
std::_Allocate<8,std::_Default_allocate_traits,0>(const unsigned int _Bytes)
std::allocator<std::_Container_proxy>::allocate(const unsigned int _Count)
std::_Container_proxy_ptr12<std::allocator<std::_Container_proxy>>::_Container_proxy_ptr12<std::allocator<std::_Container_proxy>>(std::allocator<std::_Container_proxy> & _Al_, std::_Container_base12 & _Mycont)
std::string::basic_string<char,std::char_traits<char>,std::allocator<char>>(const char * const _Ptr)
main()

让我们看看basic_string构造函数:

代码语言:javascript
复制
    basic_string(_In_z_ const _Elem* const _Ptr) : _Mypair(_Zero_then_variadic_args_t{}) {
        auto&& _Alproxy = _GET_PROXY_ALLOCATOR(_Alty, _Getal());
        _Container_proxy_ptr<_Alty> _Proxy(_Alproxy, _Mypair._Myval2);

_Container_proxy_ptr的真正含义是:

代码语言:javascript
复制
#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

在Debug中是_Container_proxy_ptr12 (最终调用了.allocate(1)),在发布时是_Fake_proxy_ptr_impl (什么都不做)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63496083

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档