3 ms·
Ok let's look at a specific example then. // foo.c #include <stdlib.h> typedef struct { int x; } s; s *make_s() { s *ret = malloc(sizeo
by haberman 11y ago
Ok let's look at a specific example then.
// foo.c
#include <stdlib.h>
typedef struct { int x; } s;
s *make_s() {
s *ret = malloc(sizeof(*ret));
ret->x = 5;
return ret;
}
void free_s(s *val) {
free(val);
}
// bar.cc
// This class is standard-layout and matches "s" from C.
class C {
int getX() { return x_; }
private:
int x_;
}
extern C* make_s();
extern void free_s(C* c);
int main(void) {
C* c = make_s();
int ret = c->getX();
free_s(c);
return ret;
}
C++ says you can only call a method on an object whose lifetime has begun. Can C begin the lifetime of a C++ object?
- Kristine1975 11y ago> Can C begin the lifetime of a C++ object? Yes. C++14 Standard §3.8p1: ...An object is said to have non-vacuous initialization if it is of a class or aggregate type and it or one of its members is initialized by a constructor other than a trivial default constructor... The lifetime of an object of type T begins when: — storage with the proper alignment and size for type T is obtained, and — if the object has non-vacuous initialization, its initialization is complete. Since class "C" is standard-layout and has a trivial default constructor (in this case none at all), assuming that malloc allocates memory that is suitably aligned for "C", the function make_s returns a pointer to an instance of C++ class "C" whose lifetime has begun. Edit: Thanks for asking btw. I use similar code in a project of mine but never actually checked whether it is actually standard-conforming.
- deleted 11y ago[deleted]