diff options
author | Berthold Stoeger <bstoeger@mail.tuwien.ac.at> | 2021-07-20 07:24:07 +0200 |
---|---|---|
committer | Dirk Hohndel <dirk@hohndel.org> | 2021-07-23 11:22:43 -0700 |
commit | f142e9a9c6ba493c09a282544da8715b3656648e (patch) | |
tree | 8b419cad550f086022acdc175a7cc7dd65e7f1e2 /core/membuffer.h | |
parent | 0c84f369c35bf416071b9ef6d5a401b457fd4a38 (diff) | |
download | subsurface-f142e9a9c6ba493c09a282544da8715b3656648e.tar.gz |
core: C++-ify membuffer
C-style memory management is a pain and nearly nobody seems to get
it right. Add a C++-version of membuffer that frees the buffer
when it gets out-of-scope. Originally, I was thinking about
conditionally adding a constructor/destructor pair when compiling
with C++. But then decided to create a derived class membufferpp,
because it would be extremely confusing to have behavioral change
when changing a source from from C to C++ or vice-versa.
Also add a comment about the dangers of returned pointer: They
become dangling on changes to the membuffer.
Signed-off-by: Berthold Stoeger <bstoeger@mail.tuwien.ac.at>
Diffstat (limited to 'core/membuffer.h')
-rw-r--r-- | core/membuffer.h | 17 |
1 files changed, 13 insertions, 4 deletions
diff --git a/core/membuffer.h b/core/membuffer.h index 6d497371c..821b0cecb 100644 --- a/core/membuffer.h +++ b/core/membuffer.h @@ -36,10 +36,6 @@ #ifndef MEMBUFFER_H #define MEMBUFFER_H -#ifdef __cplusplus -extern "C" { -#endif - #include <ctype.h> #include <stdio.h> #include <stdarg.h> @@ -50,6 +46,17 @@ struct membuffer { char *buffer; }; +#ifdef __cplusplus + +// In C++ code use this - it automatically frees the buffer, when going out of scope. +struct membufferpp : public membuffer { + membufferpp(); + ~membufferpp(); +}; + +extern "C" { +#endif + #ifdef __GNUC__ #define __printf(x, y) __attribute__((__format__(__printf__, x, y))) #else @@ -64,6 +71,8 @@ extern void put_bytes(struct membuffer *, const char *, int); extern void put_string(struct membuffer *, const char *); extern void put_quoted(struct membuffer *, const char *, int, int); extern void strip_mb(struct membuffer *); + +/* The pointer obtained by mb_cstring is invalidated by any modifictation to the membuffer! */ extern const char *mb_cstring(struct membuffer *); extern __printf(2, 0) void put_vformat(struct membuffer *, const char *, va_list); extern __printf(2, 0) void put_vformat_loc(struct membuffer *, const char *, va_list); |