This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Compiletime created instances from function.


David Sveningsson skrev:
Hi

I have my own string class and a function called s that creates an instance of a string initialized by a cstring. This can sometimes be a bit time consuming so I wrote a struct that would equal the class.

Is this even possible to do?



I have found that using compound literals seems to work. I initialize the struct with all known values (everything except the vtable pointer). I have also added a function to the struct which sets the vtable pointer from a static string class instance.



struct foo { int vtable; int classtype; int retaincount; int bytes; const char* storage; int option;

  foo* bar(){
    static UString fred;
    static foo* barney = (foo*)&fred;
    static int vtable = foobar->a;
    this->vtable = vtable;
    return this;
  }
} mystr;

#define s(str)((UString*)(&((struct foo) {1, 2, 3, sizeof(str), str, 0 }))->bar())

Running some simple tests with strings created this way seems to work. And looking at the assembly code it also seems like this should work, but is it safe to cast like this? I'm a bit worried about the function in foo.

I know that I cannot modify the object in any way but a string (of my class) created this way is not excepted to be modifiable.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]