gpt4 book ai didi

c++ - 为什么两个指针具有相同的内存地址?

转载 作者:行者123 更新时间:2023-11-30 02:16:49 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

int main()
{
char* MainBlock = new char[100];

char* SubBlock1 = new (MainBlock) char[20];

char* SubBlock2 = new (MainBlock) char [20];

cout << static_cast<void*>(SubBlock1) << " " << static_cast<void*>(SubBlock2);


}

为什么上面代码中的两个指针有相同的地址?我预计 SubBlock2 在 SubBlock 1 之后是 20 个字节。

这是否意味着即使我只有 100 个字节,我也可以使用 placement new 分配无限数量的指针?

如何使用 placement new 确保 SubBlock6 为 nullptr 或越界?

最佳答案

Why do both the pointers in the code above have the same address?

Placement new 接受它将初始化正在创建的对象的确切地址。您传递相同的地址,您将获得相同的地址。

Does this mean I can allocate an endless number of pointers with placement new even though I only have 100 bytes?

没有。每个 placement new 都会重复使用存储。您当然可以无限次重复使用存储空间,但您最多只能分配相同的 100 个字符。

How can I ensure that SubBlock6 will be a nullptr or out of bounds using placement new?

没有办法。 首先要为创建对象的新放置提供有效存储。如果不这样做,则行为未定义。

最后,您无需为新的放置而烦恼。

char *SubBlock1 = MainBlock;
char *SubBlock2 = MainBlock + 20;

分区缓冲区就好了。请确保仅删除[] MainBlock 中存储的指针值。

关于c++ - 为什么两个指针具有相同的内存地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54387297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com