在 C++ 语言中放置新运算符

placement new operator in c++ lang

本文关键字:运算符 C++ 语言      更新时间:2023-10-16

我尝试了一个简单的程序来理解放置新运算符,

#include<iostream>
#include<string.h>
using namespace std;
int main(){
        char *buf = new char[sizeof(string)];
        string *p = new (buf) string("hi");
        string *q = new string("bye");
        buf = (char*)"hello";
        cout << "buf :" << &buf << endl;
        cout << "p :" << p << endl;
        cout << "q :" << q << endl;
        cout << "buf :" << buf << endl;
        cout << "p :" << *p << endl;
        cout << "q :" << *q << endl;
        return 0;
}

如何打印buff指向的地址?&buff 将给出指针 buff 的地址,而不是它指向的地址。

我想检查 buff 和 q 是否指向相同的内存位置。

另外,如果我发表评论,buf = (char*)"hello";

Buff给出了一个不同的地址。请帮助理解。

如果要

打印地址,请转换为void* .例如:

cout << "buf :" << (void*)buf << endl;

如果您只是尝试打印char*,则使用 operator<<()char*重载,它尝试打印 C 字符串,而不是地址。

在此行

char *buf = new char[sizeof(string)];

您要求计算机为 char buf设置一个位置,但您没有为此提供任何值,因此输出是 buf 的地址。在这一行上

buf = (char*)"hello";

您将为buf保留的内存内容设置为字符串"hello",这就是您看不到地址的原因。

std::string不仅仅是

一个缓冲区。它有一个内部缓冲区,您可以通过调用 c_str() 来访问它,如下所示:

cout << "p :" << (void*)p->c_str() << endl;
cout << "q :" << (void*)q->c_str() << endl;

也就是说,您正在将buf重新分配给不同的内存位置,我不确定您是否真的知道这意味着什么。例如,您的代码不会删除对象并释放内存,在代码末尾,您可能想要类似的东西

delete q;
p->~string();
delete[] buf; // this needs to be the original pointer returned by new, not the modified one in your code!