[翻译] Effective C++, 3rd Edition, Item 51: 编写 new 和 delete 时要遵守惯例

Item 51: 编写 newdelete 时要遵守惯例

作者:Scott Meyers

译者:fatalerror99 (iTePub's Nirvana)

发布:http://blog.csdn.net/fatalerror99/

Item 50 讲解了什么时候你可能需要编写 operator newoperator delete 的你自己的版本,但是没有讲解当你这样做时必须遵循的惯例。这些规则并不难以遵循,但有一些不那么直观,所以了解它们是什么非常重要。

我们从 operator new 开始。实现一个符合惯例的 operator new 需要有正确的返回值,在没有足够的内存可用时调用 new-handling function(参见 Item 49),并做好应付无内存请求的准备。你还要避免无意中对 new 的“常规”形式的覆盖,虽然这更多的是一个 class interface(类接口)的问题,而并非是一个实现的需求,它将在 Item 52 讨论。

operator new 的返回值部分很容易。如果你能提供所请求的内存,你就返回一个指向它的指针。如果你不能,你应该遵循 Item 49 描述的规则并抛出一个 bad_alloc 类型的 exception(异常)。

然而,它也不完全那么简单,因为 operator new 实际上不止一次设法分配内存,每次失败后调用 new-handling function。在此假设 new-handling function 能做些事情释放一些内存。只有当指向 new-handling function 的指针为空时,operator new 才抛出一个 exception(异常)。

奇怪的是,C++ 要求即使请求零字节,operator new 也要返回一个合理的指针。(需要这种怪异的行为来简化语言的其它部分。)在这种情况下,一个 non-member(非成员)的 operator new 的伪代码如下:

void * operator new(std::size_t size) throw(std::bad_alloc)
{                                      // your operator new might
  using namespace std;                 // take additional params

  if (size == 0) {                     // handle 0-byte requests
    size = 1;                          // by treating them as
  }                                    // 1-byte requests

  while (true) {
   attempt to allocate size bytes;
    if (the allocation was successful)
       return (a pointer to the memory);

    // allocation was unsuccessful; find out what the
    // current new-handling function is (see below)
    new_handler globalHandler = set_new_handler(0);
    set_new_handler(globalHandler);

    if (globalHandler) (*globalHandler)();
    else throw std::bad_alloc();
  }
}

将零字节请求当作他们真的请求了一个字节来处理的窍门看起来很龌龊,但是它简单,合法,有效,无论如何,你估摸着的请求零字节这种事情发生的频率有多大呢?

你可能在不经意中还看到伪代码中将 new-handling function pointer 设置为空,然后又马上重置为它原来的值。遗憾的是,没有办法直接得到 new-handling function pointer,所以你必须调用 set_new_handler 以得知它是什么。拙劣,的确,但是也有效,至少对 single-threaded(单线程)代码没问题。在 multithreaded(多线程)环境中,你可能需要某种锁以便安全地摆布隐藏在 new-handling function 后面的(全局的)data structures(数据结构)。

Item 49 谈及 operator new 包含一个无限循环,而上面的代码明确地展示了这个循环,"while (true)" 差不多会尽其所能地无限做下去。跳出循环的唯一出路是内存被成功分配或 new-handling function 做了 Item 49 中描述的事情之一:使得更多的内存可用,安装一个不同的 new-handler,卸载 new-handler,抛出一个 bad_alloc 或从 bad_alloc 派生的 exception(异常),或不再返回。现在,new-handler 为什么要做这些事情之一已经很清楚了。如果它不这样做,operator new 内的循环永远不会停止。

很多人没有意识到 operator new member functions(成员函数)会被 derived classes(派生类)继承。这会引起一些有趣的复杂性。在前面的 operator new 伪代码中,注意那个函数设法分配 size 个字节(除非 size 是零)。因为它是传递给这个函数的 argument(实参),所以它有着明确的意义。然而,就像 Item 50 所讲的,编写一个自定义的内存管理器的最常见的原因之一是为了优化某个特定 class 的 objects 的分配,而不是某个 class 或它的任何 derived classes(派生类)的。也就是说,给定一个 class Xoperator new,这个函数的行为通常是为大小为 sizeof(X) 的 objects 调谐的——绝不会更大或者更小。然而,由于 inheritance(继承),就有可能一个 base class(基类)中的 operator new 被调用来为一个 derived class(派生类)的 object 分配内存:

class Base {
public:
  static void * operator new(std::size_t size) throw(std::bad_alloc);
  ...
};

class Derived: public Base                // Derived doesn't declare
{ ... };                                  // operator new

Derived *p = new Derived;                 // calls Base::operator new!

如果 Base 的 class-specific(类专用)的 operator new 不是被设计成应付这种情况的——它很可能不是——它处理这种局面的最佳办法就是把这个请求“错误”内存量的调用甩给 standard operator new,就像这样:

void * Base::operator new(std::size_t size) throw(std::bad_alloc)
{
  if (size != sizeof(Base))               // if size is "wrong,"
     return ::operator new(size);         // have standard operator
                                          // new handle the request

  ...                                     // otherwise handle
                                          // the request here
}

“不许动!”我听到你喊,“你忘了检查 size 是零这种 pathological-but-nevertheless-possible(病态然而可能)的情况!”实际上,我没有,还有,当你大声抱怨的时候拜托不要使用连字符。测试依然在那,它只是与 sizesizeof(Base) 的比较合在了一起。C++ 工作在一些神秘的方式中,这些方式之一就是强制规定所有的独立 objects 都具有非零的大小(参见 Item 39)。根据定义,sizeof(Base) 绝不会是零,所以如果 size 是零,请求将转发给 ::operator new,而以一种合理的方式处置这个请求就成为那个函数的职责。

如果你想要在每一个 class 的基础上控制数组的内存分配,你需要实现 operator new 的专用于数组的兄弟,operator new[]。(这个 function 通常被叫做 "array new",因为要确定 "operator new[]" 如何发音实在是太难了。)如果你决定要编写 operator new[],记住你所做的全部是分配一大块 raw memory(裸内存)——你不能针对还不存在的数组中的 objects 做任何事情。实际上,你甚至不能确定数组中会有多少个 objects。首先,你不知道每个 object 有多大。毕竟,一个 base class(基类)的 operator new[] 通过继承可以被调用来为一个 derived class objects(派生类对象)的数组分配内存,而 derived class objects(派生类对象)通常都比 base class objects(基类对象)更大。

因此,在 Base::operator new[] 中,你不能断定每一个加到数组中的 object 的大小一定是 sizeof(Base),而这就意味着,你不能断定数组中的 objects 的数量是 (bytes requested)/sizeof(Base)。第二,传递给 operator new[]size_t 参数可能比充满 objects 的内存还要大一些,因为,就像 Item 16 讲到的,dynamically allocated arrays(动态分配数组)可能包括额外的空间用于存储数组元素的数量。

编写 operator new 时,你需要遵循的惯例也就到此为止了。对于 operator delete,事情就更简单了,你需要记住的全部大约就是 C++ 保证删除空指针总是安全的,所以你需要遵循这个保证。下面是一个非成员的 operator delete 的伪代码:

void operator delete(void *rawMemory) throw()
{
  if (rawMemory == 0) return;            // do nothing if the null
                                         // pointer is being deleted

  deallocate the memory pointed to by rawMemory;
}

这个函数的成员版本也很简单,只是你必须确保检查被删除东西的大小。假设你的 class-specific(类专用)的 operator new 将“错误”大小的请求转发给 ::operator new,你也可以将“错误大小”的删除请求转发给 ::operator delete

class Base {                            // same as before, but now
public:                                 // operator delete is declared

  static void * operator new(std::size_t size) throw(std::bad_alloc);
  static void operator delete(void *rawMemory, std::size_t size) throw();
  ...
};
void Base::operator delete(void *rawMemory, std::size_t size) throw()
{
  if (rawMemory == 0) return;           // check for null pointer

  if (size != sizeof(Base)) {           // if size is "wrong,"
     ::operator delete(rawMemory);      // have standard operator
     return;                            // delete handle the request
  }
  deallocate the memory pointed to by rawMemory;
  return;
}

有趣的是,如果被删除的 object 是从一个缺少 virtual destructor(虚拟析构函数)的 base class(基类)派生出来的,C++ 传递给 operator deletesize_t 值也许是不正确的。这已经足够作为“确保你的 base classes(基类)拥有 virtual destructors(虚拟析构函数)”的原因了,除此之外,Item 7 描述了另一个,论证得更好的原因。至于当前,简单地记住如果你在 base classes(基类)中遗漏了 virtual destructors(虚拟析构函数),operator delete functions 可能无法正确工作。

Things to Remember

  • operator new 应该包含一个设法分配内存的无限循环,如果它不能满足一个内存请求,应该调用 new-handler,还应该处理零字节请求。class-specific(类专用)版本应该处理对比预期更大的区块的请求。
  • operator delete 如果收到一个空指针应该什么都不做。class-specific(类专用)版本应该处理比预期更大的区块。 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Alex Allain(Cprogramming.com)的推荐 If you want to really and truly understand C++, you must read Effective C++. After first reading Effective C++, I had a totally new appreciation for and understanding of C++. And it's not just me: this book gets 5 stars on Amazon (with over 140 reviews!). One of the reviewers even titles his review: "Don't write C++ code without it..." And I agree. I wouldn't hire someone to work for me that doesn't know the information in this book (or have plans to learn it soon). When we hire interns at my company, this is the book we give them to read. So what exactly will you learn? Scott Meyers does a great job of figuring out what little details are important, distilling the vast sea of knowledge about C++ into the 55 specific tips that are most useful for practicing C++ programmers. This isn't just a "what to do" book--it's a "why" book; every tip explains the reason for it, so you'll understand it and remember it better. In fact, even though the book is split across 55 tips, it feels like a holistic description of how to effectively use C++. Some of the specific things you'll learn: what functions are always part of a class and why it matters to you what to watch out for when writing an assignment operator How to avoid common pitfalls when creating class hierarchies how to write code designed for others to use simple techniques that can lead to huge performance improvements advanced C++ techniques, including use of the STL (with lots of examples) And much much more... If you are serious about becoming a C++ expert, buy ONE book on C++, this would be the book. (Yes, even over Bjarne Stroustrup's "The C++ Programming Language"--it's that good.) So buy Effective C++ today and write better programs tomorrow! Alex 49 Dover St. #37, Somerville, MA 02144, USA

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值