[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Interesting C++ way to allocate user data (placement new)
- From: Matthias Kluwe <mkluwe@...>
- Date: Fri, 18 May 2012 18:37:35 +0200
Hi!
2012/5/16 Pablo Pissanetzky <pablo@trickplay.com>:
> Just wanted to share this idea:
>
> void * operator new( size_t size , lua_State * L )
> {
> return lua_newuserdata( L , size );
> }
>
> Then:
>
> Foo * foo = new ( L ) Foo( constructor arguments );
"Placement new" works without overloading operator new. It's a matter
of taste if you wish to save a few keystrokes here.
Doing this depends on the returned memory being properly aligned to
hold an object of type Foo. Does anyone have a hint why this can be
assumed?
In the past I've fallen back on
Foo **f = (Foo**) lua_newuserdata( L, sizeof( Foo* ) );
*f = new Foo();
(Of course, this assumes the returned memory can hold a pointer...)
> And in __gc you have to:
>
> ( static_cast< Foo * >( lua_touserdata( L , 1 ) ) )->~Foo();
>
>
> It looks elegant but also dangerous ( in a good way, I think :)
>
> Pablo
>
> P.S. You also have to have a delete operator to deal with exceptions.
You mean, you have to deal with ~Foo() throwing exceptions? That's not
the case, hopefully (see
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.9).
Regards,
Matthias