On Thursday, 23 February 2017 at 09:52:26 UTC, Arun
Chandrasekaran wrote:
I'm trying to write an RAII wrapper on Linux.
I understand struct in D doesn't have default constructor (for
.init reasons).
I don't want to use `scope`.
Is there an elegant way to achieve this in D?
```
import core.sys.posix.pthread;
import core.sys.posix.sys.types;
/// Makes pthread_mutexattr_t cleanup easy when using exceptions
struct mutexattr_wrapper
{
/// Constructor
this(bool _)
{
if (pthread_mutexattr_init(&m_attr) != 0 ||
pthread_mutexattr_setpshared(&m_attr,
PTHREAD_PROCESS_SHARED)!= 0)
// may be I will add few more methods here
throw custom_exception("pthread_mutexattr_xxxx
failed");
}
/// Destructor
~this() { pthread_mutexattr_destroy(&m_attr); }
/// This allows using mutexattr_wrapper as
pthread_mutexattr_t
alias m_attr this;
pthread_mutexattr_t m_attr;
}
```
It reminds me of
https://w0rp.com/blog/post/an-raii-constructor-by-another-name-is-just-as-sweet/ which isn't what you want but may be interesting anyway.