为什么以及何时需要提供自己的删除器?关键字不delete
足够吗?
如果您使用智能指针来管理分配的内存以外的资源
new
,请记住传递删除器.
正如在评论中被问到的那样,我不清楚引用的文本和示例的原因是我在想某些东西是错误的,这是因为我一直在考虑智能指针只是为了动态内存管理而发明的.所以这个例子使用智能指针管理非动态内存让我感到困惑.
老人的一个很好的解释:
智能指针根本不关心动态内存本身.它只是一种在需要时跟踪某些东西的方法,并在它超出范围时销毁它.提到文件句柄,网络连接等的要点是指出它们不是动态内存,但智能指针可以管理它们就好了.
C++ Primer 5th采用伪网络连接(不定义析构函数)来说明.
坏:
struct destination; // represents what we are connecting to
struct connection; // information needed to use the connection
connection connect(destination*); // open the connection
void disconnect(connection); // close the given connection
void f(destination &d /* other parameters */)
{
// get a connection; must remember to close it when done
connection c = connect(&d);
// use the connection
// if we …
Run Code Online (Sandbox Code Playgroud) 我很好奇delete []如何计算分配内存的大小.当我做的事情:
int* table = new int[5];
delete[] table;
Run Code Online (Sandbox Code Playgroud)
我明白表的内存是释放的.但是,如果我将指针重新分配给某个不同的表,会发生什么.
int* table = new [5];
int* table2 = new [9];
table = table2;
delete[] table;
Run Code Online (Sandbox Code Playgroud)
我可以免费使用5或9号桌子吗?我对new []和delete []如何共享有关其大小的信息感兴趣.或许我错过了一些必不可少的东西.
我遇到的问题是,据我所知,删除操作符应该是一个静态函数,但有时编译器(VC++)似乎将它视为动态.
鉴于:
class Base
{
public:
void* operator new(size_t size) { /* allocate from custom heap */ }
void operator delete(void *p) { customFree(p, sizeof(Base)); }
Base() {}
virtual ~Base() {}
};
class Derived: public Base
{
public:
void* operator new(size_t size) { /* allocate from custom heap */ }
void operator delete(void *p) { customFree(p, sizeof(Derived)); }
Derived() {}
virtual ~Derived() {}
}
Run Code Online (Sandbox Code Playgroud)
我看到的是删除基指针将导致调用Derived::opeator
删除.
Base *p = new Derived();
delete p; //calls Derived::operator delete
Run Code Online (Sandbox Code Playgroud)
如果我没有定义任何析构函数,那么我得到了我预期的结果:调用Base …
我知道它们在语法上是如何不同的,并且C++使用new,而C使用malloc.但他们如何运作,在一个高级别的解释?