Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually Call a C++ Object's Initializer in C

I am working on a small application that was written in C++ and would like to use on my platform. Unfortunately, our cross-compile toolchain only (reliably) provides a C compiler. I looked at the application, and it is fairly simple and only uses C++-specific idioms in a few places, so I thought I'd just convert it to C code by hand.

I bumped across one line that I'm not sure how to handle. The code is using Termios to open a new port to talk to a TTY stream, and initializes the Termios struct using the new keyword.

termios *settings = new termios();

As I understand it, the new keyword, in addition to allocating the appropriate memory, calls the object's initializer. In C, after I allocate memory with malloc, can I manually call the initializer? Do I need to?

I have a feeling that I'm misunderstanding something obvious / fundamental or that I'm looking at this all wrong. I'm not very accustomed to C++ code.

edit: I seem to have caused some confusion. The line of code above is creating a new termios struct as defined in termios.h, part of the standard libraries on most implementations of C.

like image 739
Woodrow Barlow Avatar asked Jul 09 '26 14:07

Woodrow Barlow


1 Answers

The line

termios *settings = new termios();

allocates memory for a termios object and value-initializes it. Since termios is a POD, the equivalent C would be

struct termios* settings = calloc(1, sizeof(*settings));

or

struct termios* settings = malloc(sizeof(*settings));
memset(settings, 0, sizeof(*settings));

and of course the equivalent of delete settings would be free(settings).

like image 156
Casey Avatar answered Jul 12 '26 03:07

Casey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!