コンストラクタとデストラクタを通るときに情報を出力するようにすると、
何が起きているかわかりやすくなるかもしれません。
コード:
#include <cstdio>
#include <string>
#include <vector>
using std::string;
struct hoge : public string {
hoge(): string() {
printf( "hoge %p constructer\n" , (void*)this );
}
hoge( const char* s ): string( s ) {
printf( "hoge %p constructer content=%s (%p)\n" , (void*)this , s , (void*)s );
}
hoge( const hoge& h ): string( h ) {
printf( "hoge %p constructer copy from %p\n" , (void*)this , (void*)&h );
}
~hoge() {
printf( "hoge %p destructer\n" , (void*)this );
}
hoge& operator=( const hoge& h ) {
printf( "hoge %p set hoge %p\n" , (void*)this , (void*)&h );
*((string*)this) = h;
return *this;
}
hoge& operator=( const char* s ) {
printf( "hoge %p set content %s (%p)\n" , (void*)this , s , (void*)s );
*((string*)this) = s;
return *this;
}
const char* c_str() const {
const char* ret = ((string*)this)->c_str();
printf( "hoge %p c_str() = %p\n" , (void*)this , (void*)ret );
return ret;
}
};
const char* test( const hoge& str )
{
return str.c_str();
}
int main( void )
{
const char* str1 = test( "1234" );
const char* str2 = test( "5678" );
printf( "str1 = %s (%p)\n" , str1 , (void*)str1 );
printf( "str2 = %s (%p)\n" , str2 , (void*)str2 );
return 0;
}
【修正】std::vectorを用いたtest関数(No: 2と同じ)を削除