Gotcha #63: Confusing Scope and Activation of Member new and delete
Gotcha条款63:Member New和Member Delete之生存期与活动空间的迷惑
当一个类别的对象被创建和销毁时,其所声明的member operator new和member operator delete会被唤起。施行分配的表达式所处的实际生存空间(scope)与此无关:
class String {
public:
void *operator new( size_t ); // member operator new
void operator delete( void * ); // member operator delete
void *operator new[]( size_t ); // member operator new[]
void operator delete [] ( void * ); // member operator delete[]
String( const char * = "" );
// . . .
};
void f() {
String *sp = new String( "Heap" ); // 使用 String::operator new
int *ip = new int( 12 ); // 使用 ::operator new
delete ip; // 使用 :: operator delete
delete sp; // 使用 String::delete
}
分配操作所处的生存空间无关大局,只有被分配对象的型别才真正决定哪一个分配函数被调用:
String::String( const char *s )
: s_( strcpy( new char[strlen(s)+1], s ) )
{}
字符数组在class String的scope内被分配内存,但分配使用的是global array new,而非String的那个array new——因为型别不同,char并不是String。经由显式的限定(explicit qualification),我们可以这样做:
String::String( const char *s )
: s_( strcpy( reinterpret_cast<char *>
(String::operator new[](strlen(s)+1 )),s ) )
{}
如果我们能够使用形如String::new char[strlen(s)+1]的语句来调用String的operator new[]就好了,但这是非法的,行不通。(尽管我们可以使用::new的形式来调用global operator new和global operator new[],使用::delete的形式来调用global operator delete和global operator delte[]。)
本文地址:http://com.8s8s.com/it/it29299.htm