static_cast< ? > 형변환 연산자?

nayana의 이미지

static_cast형변환연산자에서 에러가 납니다.

a.cpp: In static member function `static void Rational::expandTheFreeList()':
a.cpp:112: invalid static_cast from type `char*' to type `NextOnFreeList*'
a.cpp:119: invalid static_cast from type `char*' to type `NextOnFreeList*'

char* 에서 NextOnFreeList*변한이 타당하지 못하다고 나옵니다.
소스는 다음과 같습니다.
      1 #include <cstdio>
      2 #include <new>
      3
      4 #include <sys/time.h>
      5 #include <unistd.h>
      6
      7 struct timeval Start, End;
      8
      9 //--------------------------------------------------------------------------------------------
     10 void t_Start( void )
     11 //--------------------------------------------------------------------------------------------
     12 {
     13     gettimeofday( &Start, NULL );
     14 }
     15
     16 //--------------------------------------------------------------------------------------------
     17 void t_End( void )
     18 //--------------------------------------------------------------------------------------------
     19 {
     20     gettimeofday( &End, NULL );
     21 }
     22
     23 //--------------------------------------------------------------------------------------------
     24 double tval( void )
     25 //--------------------------------------------------------------------------------------------
     26 {
     27     double t1       = ( End.tv_sec  - Start.tv_sec )  / 1.0; // 초
     28     double t2       = ( End.tv_usec - Start.tv_usec ) / 1.0; // 마이크로 초
     29     double interval = ( ( ( t1 * 1000000.0 ) + t2 ) / 1000000.0 );
     30
     31     return interval;
     32 }
     33
     34 //--------------------------------------------------------------------------------------------
     35 void Result( double t )
     36 //--------------------------------------------------------------------------------------------
     37 {
     38     printf( "%.6f 초\n", t );
     39 }
     40
     41 //============================================================================================
     42 class NextOnFreeList
     43 {
     44 public :
     45     NextOnFreeList* next;
     46 };
     47 //============================================================================================
     48
     49 //============================================================================================
     50 class Rational
     51 {
     52 public :
     53     Rational( int a = 0, int b = 1 )
     54         :n( a ), d( b )
     55         {
     56
     57         }
     58
     59 //------------------------------------------------------------------------------
     60     inline void* operator new( size_t size )
     61     {
     62         if ( 0 == freeList )
     63         {
     64             expandTheFreeList();
     65         }
     66
     67         NextOnFreeList* head = freeList;
     68         freeList             = head->next;
     69
     70         return head;
     71     }
     72 //------------------------------------------------------------------------------
     73
     74 //------------------------------------------------------------------------------
     75     inline void  operator delete( void* doomed, size_t size )
     76     {
     77         NextOnFreeList* head = static_cast< NextOnFreeList* >( doomed );
     78         //NextOnFreeList* head = ( NextOnFreeList* ) doomed;
     79         head->next           = freeList;
     80         freeList             = head;
     81     }
     82 //------------------------------------------------------------------------------
     83
     84 //------------------------------------------------------------------------------
     85     static void  newMemPool( void )
     86     {
     87         expandTheFreeList();
     88     }
     89 //------------------------------------------------------------------------------
     90
     91 //------------------------------------------------------------------------------
     92     static void deleteMemPool( void )
     93     {
     94         NextOnFreeList* nextPtr;
     95
     96         for ( nextPtr = freeList; nextPtr != NULL; nextPtr = freeList )
     97         {
     98             freeList = freeList->next;
     99             delete[] nextPtr;
    100         }
    101     }
    102 //------------------------------------------------------------------------------
    103
    104 private :
    105     static NextOnFreeList* freeList;
    106
    107 //------------------------------------------------------------------------------
    108     static void expandTheFreeList( void )
    109     {
    110         size_t size = ( sizeof( Rational ) > sizeof( NextOnFreeList* ) ) ? sizeof( Rational ) : sizeof( NextOnFreeList* );
    111
    112         NextOnFreeList* runner = static_cast< NextOnFreeList* > ( new char[ size ] );
    113     //  NextOnFreeList* runner = ( NextOnFreeList* ) new char[ size ];
    114
    115         freeList = runner;
    116
    117         for ( int i = 0; i < EXPANSION_SIZE; ++i )
    118         {
    119             runner->next = static_cast< NextOnFreeList* > ( new char[ size ] );
    120             //runner->next = ( NextOnFreeList* ) new char[ size ];
    121
    122             runner = runner->next;
    123         }
    124
    125         runner->next = 0;
    126     }
    127 //------------------------------------------------------------------------------
    128
    129     enum { EXPANSION_SIZE = 32 };
    130     int n, d;
    131 };
    132 //============================================================================================
    133
    134 NextOnFreeList* Rational::freeList = 0;
    135
    136 int main ( void )
    137 {
    138     Rational* array[ 1000 ];
    139
    140     Rational::newMemPool();
    141
    142     t_Start();
    143
    144     for ( int j = 0; j < 50000; ++j )
    145     {
    146         for ( int i = 0; i < 1000; ++i )
    147         {
    148             array[ i ] = new Rational( i );
    149         }
    150
    151         for ( int i = 0; i < 1000; ++i )
    152         {
    153             delete array[ i ];
    154         }
    155     }
    156
    157     t_End();
    158     Result( tval() );
    159
    160     Rational::deleteMemPool();
    161
    162     return 0;
    163 }

stic_cast 연산자 대신 c에서 해던 방식으로 강제로 형변환을 시키면 문제가 없습니다. 하지만 static_cast 연산자는 허용하지가 않습니다. 하지만 위의 소스를 보시는거와 같이 void 형태는
캐스팅이 잘됩니다.
( static_cast< NextOnFreeList*>doomed ); 나머지 2개는 캐스팅이 안됩니다.

cdpark의 이미지

이상한 코드군요. Rational과 NextOnFreeList* 를 같은 메모리 영역에 저장하려는 게 목표인가요? 그렇다면 그냥 union을 쓰지 않는 이유라도??

nayana의 이미지

Quote:
Rational과 NextOnFreeList* 를 같은 메모리 영역에 저장하려는 게 목표인가요? 그렇다면 그냥 union을 쓰지 않는 이유라도??

같은 메모리 영역에 할려는것은 맞습니다.
union은 무슨 말씀이신지요?
익명 사용자의 이미지

님이 하고자하는 바는 reinterprete_cast가 하고자 하는바입니다.
reinterprete_cast를 사용하세요.

nayana의 이미지

reinterprete_cast 연산자는 일단 비표준형 형변환으로 알고 있습니다. reinterprete_cast 형변환연산자를 쓰지 않는 이유는 충분히 static_cast 연산자로 reinterprete_cast 형변환 연산자를 대치해서 쓸수있고
reinterprete_cast 형변환 연산자를 사용할 경우 비 표준 형변환이다보니 심각한 실행 오류를 범할수가 있고 다른 플랫폼에서는 프로그램이 다르게 작동되는 문제를 초래할수가 있기 때문입니다.

hey의 이미지

nayana wrote:
reinterprete_cast 연산자는 일단 비표준형 형변환으로 알고 있습니다. reinterprete_cast 형변환연산자를 쓰지 않는 이유는 충분히 static_cast 연산자로 reinterprete_cast 형변환 연산자를 대치해서 쓸수있고
reinterprete_cast 형변환 연산자를 사용할 경우 비 표준 형변환이다보니 심각한 실행 오류를 범할수가 있고 다른 플랫폼에서는 프로그램이 다르게 작동되는 문제를 초래할수가 있기 때문입니다.

static_cast는 형변환이 허용되어 있는 형 사이에서만 사용 가능합니다. 부모와 자식 클래스 사이의 캐스팅이나 int에서 long, float에서 int 등이 그것입니다. reinterpret_cast<>가 C 형식의 캐스트와 동일한 동작을 하며 이러한 캐스트가 지양되는 것은 구현 의존적이기 때문이지 뭐 심각한 문제가 있는 것은 아닙니다. :]


----------------------------
May the F/OSS be with you..


cdpark의 이미지

nayana wrote:

reinterprete_cast 형변환 연산자를 사용할 경우 비 표준 형변환이다보니 심각한 실행 오류를 범할수가 있고 다른 플랫폼에서는 프로그램이 다르게 작동되는 문제를 초래할수가 있기 때문입니다.

char * 형에서 NextOnFreeList* 형으로의 변환이 이에 해당합니다. :cry:

doldori의 이미지

nayana wrote:
reinterprete_cast 형변환연산자를 쓰지 않는 이유는 충분히 static_cast 연산자로 reinterprete_cast 형변환 연산자를 대치해서 쓸수있고

잘못 알고 계십니다. static_cast<T'>(T)는 T --> T' 또는 T' --> T 의 변환이 허용될
때만 쓸 수 있는 것이며 reinterpret_cast를 대치할 수 있는 것은 아닙니다.
reinterpret_cast는 전혀 관련이 없는 형변환을 할 때(지금처럼 char* -->
NextOnFreeList*) 쓰는 것이며, 따라서 reinterpret_cast를 쓴 코드는 이식성이
없을 가능성이 높습니다.
nayana의 이미지

그렇군요...제가 잘못알고 있었습니다.^^;

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.