关于嵌套类的运算符new的重载解析
Overload resolution of operator new regarding nested classes
如果我为具有嵌套类的类重载运算符new
和delete
:
class A
{
public:
static void* operator new(size_t);
static void operator delete(void*);
class B;
}
A::B
对象实例的分配和A::B
对象内的分配会使用重载的A::new
和A::delete
还是全局默认值?
首先,您不需要过载new
或delete
的可能性非常高,并且应该避免这样做。
尽管如此,重载运算符将应用于类A
,而不是类A::B
。如果您希望B具有重载运算符,那么还需要在类B
中重载它们。
关于如何过载new
和delete
的示例:http://www.cprogramming.com/tutorial/operator_new.html
否。
class A
{
public:
A(){printf("An");}
~A(){}
static void* operator new(size_t t){
printf("A newn");
::operator new(t);
}
static void operator delete(void* t){
printf("A deleten");
::operator delete(t);
}
void check_B(){
b = new B();
::operator delete(b);
}
class B{
public:
B(){}
};
B* b;
};
class C : public A {
};
测试:
int main(void)
{
A* a = new A;
printf("ncheck ------n");
a->check_B();
printf("ncheck ------n");
delete a;
C* c = new C;
A* cc = new C;
delete c;
delete cc;
return 0;
}
输出:
新的
检查------
检查------
删除
一种新的
一种新的
删除
删除
运行成功(总时间:64ms)
valgrind:
==9318==
==9318== HEAP SUMMARY:
==9318== in use at exit: 0 bytes in 0 blocks
==9318== total heap usage: 4 allocs, 4 frees, 25 bytes allocated
==9318==
==9318== All heap blocks were freed -- no leaks are possible
==9318==
==9318== For counts of detected and suppressed errors, rerun with: -v
==9318== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
它甚至不会为new A[]
调用,除非您也重载operator new[]()
。您需要相应地为嵌套类A::B
重载它们。然而,正如我们所看到的,它们将被调用于从A.派生的类
测试,测试,测试。做测试总比不做测试好。作者:me.
相关文章:
- 重载运算符new[]的行为取决于析构函数
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- 为什么 std::make_shared 无法编译带有已删除运算符 new 的类型?
- 为什么 std::vector 使用 std::分配器而不是运算符 new 和 delete?
- 运算符 new 的执行顺序和构造函数的参数
- 如何分配适合容纳 T 类型对象的缓冲区(可能过度对齐、可能有运算符 new 等)
- 重载运算符 new 和运算符 delete 带有三个参数
- 为什么运算符"new"需要指针才能工作?
- 重载运算符 new(),为什么构造函数被调用两次?
- 为什么运算符 new[] 为数组的大小分配内存?
- 在混合 c 和 c++ 代码中使用运算符 new
- 重载运算符 new/new[] 删除/删除[] 全局C++
- 为什么允许重新定义全局运算符 new(size_t)?
- 无法访问使用运算符 new() 分配的内存
- 显式调用"运算符 new"后无法访问对象的函数
- c++ 运算符 new[]/delete [] 是否调用运算符 new/delete?
- 崩溃时间(运算符 new(无符号 int)+22)
- 继承类上的运算符new和delete.操作员删除未执行
- 运算符new[]不接收额外的字节
- 如果我在C++中分配一个带有运算符 new[] 的对象数组,但单独释放它们是否仍然构成内存泄漏