在 C++ 语言中放置新运算符
placement new operator in c++ lang
我尝试了一个简单的程序来理解放置新运算符,
#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!
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<