Dza*_*ata 2 c++ string overriding new-operator
我们和我的朋友一起制作了一个带有覆盖 new 和 new[] 运算符的程序。我发现当我尝试使用以下代码创建字符串数组时:
string* Test1 = new string[10];
Run Code Online (Sandbox Code Playgroud)
函数返回无效指针(通常它的值向前移动 8 位,我正在将程序编译到 x64 平台)。我们的 new[] 函数看起来像这样:
void* operator new[] (size_t e)
{
void* Test2 = operator new(e);
return Test2;
}
Run Code Online (Sandbox Code Playgroud)
在返回前用调试器运行程序时,指针的Test2值为 0x0000000009dfaa90,但值Test1变为 0x0000000009dfaa98。
这种情况只发生在字符串类型中。我试过对“int[10]”、“string* [10]”和我的一个类的对象做同样的事情,但只有在处理字符串时才会出现问题,还有代码:
string* Test1 = new string;
Run Code Online (Sandbox Code Playgroud)
工作得很好。
有人可以解释一下为什么会发生这种情况以及如何使其正常工作吗?
PS:我们使用的是 Visual Studio 2012 专业版
编辑:我刚刚测试了它未被覆盖,new[]并且在创建字符串表时它的工作方式相同(返回的指针不是函数尝试的指针return),所以它似乎不是问题。有人能解释一下为什么指针的值只对字符串数组改变,如果似乎没有任何其他指令可以改变它,它会如何改变?
答案是new/delete和new[]/delete[]是不同的。你可能不会感到惊讶,但另一个令人惊讶的消息(不是双关语)是new运营商和operator new不同的。
这是测试问题的示例代码(您可以更改tested_typetypedef 的内容):
#include <iostream>
#include <vector>
#include <string>
typedef std::string tested_type;
void* Test2;
size_t allocated_mem_size;
void* operator new[] (size_t e)
{
void* retaddr = operator new(e);
Test2 = retaddr;
allocated_mem_size = e;
return retaddr;
}
int _tmain(int argc, _TCHAR* argv[])
{
void* Test1 = new tested_type[10];
std::cout << "sizeof(tested_type)*10 is " << sizeof(tested_type)*10 << "\n"
<< "Test1 is " << Test1 << "\n"
<< "Test2 is " << Test2 << "\n"
<< "operator new[] was called with e == " << allocated_mem_size << "\n"
<< "What's in the missing bytes? " << *(size_t*)Test2 << "\n";
}
Run Code Online (Sandbox Code Playgroud)
我机器上的输出是:
sizeof(tested_type)*10 is 280
Test1 is 0085D64C
Test2 is 0085D648
operator new[] was called with e == 284
What's in the missing bytes? 10
Run Code Online (Sandbox Code Playgroud)
(注意 - 我有一个 32 位编译器)
如果我们tested_type改为 int,我们有:
sizeof(tested_type)*10 is 40
Test1 is 0070D648
Test2 is 0070D648
operator new[] was called with e == 40
What's in the missing bytes? 3452816845
Run Code Online (Sandbox Code Playgroud)
现在,如果我们tested_type改为std::vector<int>,我们有
sizeof(tested_type)*10 is 160
Test1 is 004AD64C
Test2 is 004AD648
operator new[] was called with e == 164
What's in the missing bytes? 10
Run Code Online (Sandbox Code Playgroud)
现在我们在这里看到一个模式:添加的额外字节等于分配的元素数。此外,添加字节的唯一时间是类型不平凡的时候......
就是这样!
调整地址的原因是new[]要存储元素数量。我们之所以需要在某些情况下存储元素数量,而在其他情况下不需要,是因为delete[]调用析构函数,并且delete[](但不是delete只为单个元素调用析构函数)必须以某种方式知道它必须销毁多少个元素。不需要为像 那样的基本类型调用析构函数int,因此new[]不存储有多少。
(另外,我推荐std::vector- 它只是有效)
| 归档时间: |
|
| 查看次数: |
860 次 |
| 最近记录: |