C++ Gotchas 条款63:Member New和Member Delete之生存期与活动空间的迷惑 (转)

C++ Gotchas 条款63:Member New和Member Delete之生存期与活动空间的迷惑 (转)[@more@]

Gotcha #63: Confusing SCOpe and Activation of Member new and deleteXML:namespace prefix = o ns = "urn:schemas-microsoft-com:Office:office" />

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

(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[]。)


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/10748419/viewspace-987883/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/10748419/viewspace-987883/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
《Verilog and SystemVerilog Gotchas》是一本关于Verilog和SystemVerilog语言的电子书。它旨在帮助读者避免在编写Verilog和SystemVerilog代码时常见的陷阱和错误。 这本电子书对于那些对Verilog和SystemVerilog语言有一定了解的人来说尤为有用。它研究了许多常见的问题和错误,并提供了简明扼要的解释和示例代码。 《Verilog and SystemVerilog Gotchas》首先介绍了Verilog语言的基础知识,包括模块化设计概念、数据类型、运算符和控制结构等。然后,它讨论了一些常见但容易被忽视的问题,例如在条件语句中的敏感列表、并发语句中的竞争条件和时序不确定性。 接下来,这本电子书向SystemVerilog语言,介绍了其扩展功能,如对象导向编程、断言和宏定义。它还强调了一些SystemVerilog中常见的问题,如虚拟接口的使用和任务和函数的调用方式。 此外,《Verilog and SystemVerilog Gotchas》也涉及了Simulator和Synthesizer之间的一些差异和注意事项。它帮助读者理解不同的仿真和综合工具之间的差异,并提供了一些建议,以避免由于这些差异而引起的问题。 总的来说,这本电子书是一种很好的资源,能够帮助工程师和学生更好地理解和使用Verilog和SystemVerilog语言。它提供了许多实用的建议和示例,可以帮助读者避免在编写代码时常见的陷阱和错误。无论是初学者还是有经验的用户,都可以从这本书中获益,提高他们在编写Verilog和SystemVerilog代码时的效率和准确性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值