我正在使用Centos平台上的共享库和应用程序[clang ++,llvm3.9.0和libc ++],并且库和应用程序都会重载它们自己的operator new和operator delete。
除1例外,一切正常。在调用std :: string的copy构造函数时,总是调用应用程序端的 operator new :
以下是senario:
std::string str1 ( "A very strange issue on CentOS using clang and libc++" ); //operator new of library side called.
std::string str2(str1); //operator new of application side called. WHY??
对于库侧调用两个案例的operator delete 。
以下是运行以下代码时的日志:
====================================================
operator new in shared library
operator new called Application side
operator delete in shared library
operator delete in shared library
====================================================
共享库侧操作员new和delete:
void * operator new ( size_t len ) throw ( std::bad_alloc )
{
printf("operator new in shared library\n");
void * mem = malloc( len );
if ( (mem == 0) && (len != 0) ) throw std::bad_alloc();
return mem;
}
void * operator new[] ( size_t len ) throw ( std::bad_alloc )
{
printf("operator new[] in shared library\n");
void * mem = malloc( len );
if ( (mem == 0) && (len != 0) ) throw std::bad_alloc();
return mem;
}
void operator delete ( void * ptr ) throw()
{
printf("operator delete in shared library\n");
if ( ptr != 0 ) free ( ptr );
}
void operator delete[] ( void * ptr ) throw()
{
printf("operator delete[] in shared library\n");
if ( ptr != 0 ) free ( ptr );
}
应用程序端操作员new和operator delete:
void * operator new ( size_t len ) throw ( std::bad_alloc )
{
void * mem = malloc ( len );
printf("operator new called Application side\n");
if ( (mem == 0) && (len != 0) ) throw std::bad_alloc();
return mem;
}
void * operator new[] ( size_t len ) throw ( std::bad_alloc )
{
void * mem = malloc ( len );
printf("operator new[] called Application side\n");
if ( (mem == 0) && (len != 0) ) throw std::bad_alloc();
return mem;
}
void operator delete ( void * ptr ) throw()
{
printf("operator delete[] called Application side\n");
if ( ptr != 0 )free ( ptr );
}
void operator delete[] ( void * ptr ) throw()
{
printf("operator delete[] called Application side\n");
if ( ptr != 0 ) free ( ptr );
}
请帮忙。
答案 0 :(得分:8)
简短回答:不要这样做。
只应该有一个替换operator new
(好吧,有一堆风味,如noexcept
和[]
等,但只有一种风味)。< / p>
如果您有多个,那么 - 正如您所发现的那样 - 不清楚调用哪一个,并且您可以获得对new和delete的不匹配调用,这是对未定义行为的快速访问。
我可以解释为什么你得到的是你报告的确切行为,但它与内联模板和外部模板有关,而且它并不重要。 operator new
有两个替换函数,这就是问题所在。