1

我尝试了一个简单的程序来理解placement new 运算符,

#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 给出了不同的地址。请帮忙理解。

4

3 回答 3

1

在这条线上

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

您要求计算机为 char 设置一个位置,buf但您对此没有任何价值,因此输出是buf. 在这条线上

buf = (char*)"hello";

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

于 2013-10-20T11:27:35.133 回答
1

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

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

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

于 2013-10-20T11:31:22.000 回答
1

Astd::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!
于 2013-10-20T11:33:32.370 回答