Reputation: 7539
Consider a program with mixed C and C++ code. The C++ part contains a class which dinamically allocates a C-style typedef struct
. Minimal example:
obj.h (C-code)
typedef struct _Ctype {
int i;
} Ctype;
class.hpp (C++ code)
struct A {
struct _Ctype *x;
A(int i);
~A();
};
class.cpp (C++ code)
#include "class.hpp"
extern "C" {
#include "obj.h"
}
A::A(int i)
{
x = new struct _Ctype;
x->i = i;
}
A::~A()
{
delete(x);
}
main.cpp (C++ code, main program)
#include "class.hpp"
int main()
{
A a(3);
return 0;
}
(The rationale for this design originates from this answer)
Is it safe (i.e., no UB) to use a new
expression to allocate a C-style type struct _Ctype
, as in the code above, or should one better use the C-style malloc
/free
?
class.cpp (C++ code, alternative)
#include <cstdlib>
#include "class.hpp"
extern "C" {
#include "obj.h"
}
A::A(int i)
{
x = (struct _Ctype *)malloc(sizeof(struct _Ctype));
x->i = i;
}
A::~A()
{
free(x);
}
ADDITION
To clarify the question after some comments below: In the minimal example above, all the code is compiled with a C++ compiler. One can however think to use the C++ code in conjunction with a C library. The question can then be reformulated as follows:
typedef struct
via a C++ code, can the C library safely use the allocated variable? If so, are the alternatives given above both safe?Note that one could also think to allocate the memory for Ctype
through a C function, so that the C++ code only manages a pointer to it, for example:
obj.h (C-code)
typedef struct _Ctype {
int i;
} Ctype;
Ctype *allocate_Ctype();
void deallocate_Ctype(Ctype* p);
obj.C (C-code)
#include <stdlib.h>
#include "obj.h"
Ctype *allocate_Ctype()
{
return (Ctype *)malloc(sizeof(Ctype));
}
void deallocate_Ctype(Ctype *p)
{
free(p);
}
class.cpp (C++ code)
#include "class.hpp"
extern "C" {
#include "obj.h"
}
A::A(int i)
{
x = allocate_Ctype();
x->i = i;
}
A::~A()
{
deallocate_Ctype(x);
}
(Note: of course the copy constructor and operator assignment of class A need to be properly defined, the code serves as illustration of the question)
Upvotes: 1
Views: 309
Reputation: 171127
As long as the deallocation only ever happens under your control and using a delete
expression, there is no problem at all. The C code interacting with the structure does not care how it was allocated.
Side note: the name _Ctype
is not legal in C++, as it starts with an underscore followed by an uppercase letter. Such names (as well as names containing double underscore) are reserved for the compiler & standard library.
Upvotes: 4