lundi 7 avril 2014

Class/Struct definition local to a function.


You may know or not that defining a class or struct inside a function is possible but you may not be aware of all the issue you will meet when using that with the old C++98.
First thing, if you are using C++11 you can pass away, because in all case that feature will be correctly handle by recent compiler and debugger.
Now if your are still using a C++98 compiler or an old GCC, stay here and read the following:)

Definition in a function

In most case the following code will be Ok.

int function() { 
   typedef struct myStruct { 
       int num; 
       myStruct (int n): num(n){} 
       myStruct(const myStruct& ro):num(ro.num){} 
    } mystruct_t; 

  mystruct_t t(2);

  return t.num;
} 


But want will happened if you try to use that struct with an STL’s container, like vector, deque, etc….. Example

int function() { 
   typedef struct myStruct { 
       int num; 
       myStruct (int n): num(n){} 
       myStruct(const myStruct& ro):num(ro.num){} 
    } mystruct_t; 

  std::deque<mystruct_t> dq(10, mystruct_t(2));
  
   return dq[0].num;
} 

In fact here we have 2 different scenario:
  1. you are using GCC and it will not compile, because it’s not a C++98 compliant code
  2. you are using VC++2008 and it will compile, but you will meet weird debugger behavior on that piece of code.

Explanation

In C++98, you cannot use local class or struct with template type. This restriction is part of the standard. The reasoning was originally that local structures don't really have a names and thus it would be impossible to instantiate a template with them.

So as said if VC++2008 allow that code to compile, you will not be able to see what you have in your deque… Like in the snapshot below.

DebuggerError

My conclusion

Try to avoid that kind of code until you get the new C++11, because the portability across platform is not guarantee by the standard and that debugging and maintaining them is really hard. Define your class or struct outside of the function.

Aucun commentaire :

Enregistrer un commentaire