首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::realloc

Defined in header <cstdlib>

?

?

void* realloc( void* ptr, std::size_t new_size );

?

?

重新分配给定的内存区域。必须先由std::malloc(),,,std::calloc()std::realloc()还没有被释放std::free(),否则,结果是未定义的。

重新分配是由以下两种方法之一完成的:

a%29扩大或缩小现有区域ptr,如果可能的话。该地区的内容保持不变,直至较小的新和旧的大小。如果展开区域,则数组的新部分的内容未定义。

B%29分配大小的新内存块new_size字节,复制大小等于新旧大小的内存区域,并释放旧块。

如果内存不足,则不会释放旧内存块并返回空指针。

如果ptr为空指针,其行为与调用std::malloc%28new_size29%。

如果new_size为零,行为为实现定义:空指针可以返回%28,在这种情况下,旧内存块可能被释放也可能不会释放,%29或者可能返回一些非空指针,这些指针可能不会用于访问存储。

The following functions are required to be thread-safe: The library versions of operator new and operator delete User replacement versions of global operator new and operator delete std::calloc, std::malloc, std::realloc, std::aligned_alloc (since C++17) Calls to these functions that allocate or deallocate a particular unit of storage occur in a single total order, and each such deallocation call happens-before the next allocation (if any) in this order.

(since C++11)

  • 的库版本operator newoperator delete
  • 全局用户替换版本operator newoperator delete
  • std::calloc,,,std::malloc,,,std::realloc,,,std::aligned_alloc%28自C++17%29

对分配或释放特定存储单元的这些函数的调用是以单个总顺序进行的,并且每个这样的释放调用都会发生。发生-之前下一次按此顺序分配%28(如果有%29)。

%28自C++11%29

参数

ptr

-

pointer to the memory area to be reallocated

new_size

-

new size of the array

返回值

成功后,返回指向新分配内存开始的指针。返回的指针必须用std::free(),原始指针ptr无效,并且对它的任何访问都是无效的。未定义行为%28,即使重新分配是就地的%29。

失败时,返回一个空指针。原始指针ptr仍然有效,可能需要用std::free()...

注记

因为重新分配可能涉及按字节复制%28,而不管它是以%27展开还是收缩%29,只有TriviallyCopyable调用之后,类型可以安全地访问内存块保留的部分。realloc...

一些非标准库定义了一个类型特征“BitwiseMoable”或“Relocable”,它描述的类型是%27T具有:

  • 外部引用%28例如。列表或树的节点,这些节点包含对另一个元素%29的引用,以及
  • 内部参考资料%28例如。成员指针,它可能保存另一个成员%29的地址。

这种类型的对象可以在重新分配其存储后访问,即使它们的复制构造函数并不简单。

二次

代码语言:javascript
复制
#include <cstdlib>
#include <new>
#include <cassert>
 
class MallocDynamicBuffer
{
    char* p;
public:
    explicit MallocDynamicBuffer(std::size_t initial = 0) : p(nullptr) {
       resize(initial);
    }
    ~MallocDynamicBuffer() { std::free(p); }
    void resize(std::size_t newSize) {
        if(newSize == 0) { // this check is not strictly needed, 
            std::free(p);  // but zero-size realloc is deprecated in C
            p = nullptr;
        } else {
            if(void* mem = std::realloc(p, newSize))
                p = static_cast<char*>(mem);
            else
                throw std::bad_alloc();
        }
    }
    char& operator[](size_t n) { return p[n]; }
    char operator[](size_t n) const { return p[n]; }
};
 
int main()
{
    MallocDynamicBuffer buf1(1024);
    buf1[5] = 'f';
    buf1.resize(10); // shrink
    assert(buf1[5] == 'f');
    buf1.resize(1024); // grow
    assert(buf1[5] == 'f');
}

二次

另见

c不动产文件c

*。

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com