C ++ string in C struct, is this illegal?

struct run_male_walker_struct {
        string male_user_name;
        string show_name;
};
typedef struct run_male_walker_struct run_male_walker_struct_t;

in another function:

run_male_walker_struct_t *p = malloc(sizeof(struct run_male_walker_struct));

question is it illegal? Since a string is a class, its size cannot be determined by sizeof ().

+5
source share
8 answers

This is illegal, but not for the reasons you think about.

The difference between std::malloc()/ std::free()and new/ deleteis that the latter will call constructors / destructors, and the former will not. Expression

void* p = std::malloc(sizeof(run_male_walker_struct))

will return blob of uninitialized memory on which the constructor is not called. You should not touch it with a ten-foot pole - with the exception of calling the constructor on it:

run_male_walker_struct* pw = new(p) run_male_walker_struct;

If you do this, you will also have to do the opposite:

pw->~run_male_walker_struct();

before freeing up memory:

std::free(p);

, .
- (, ). , . new delete . , std::vector .

+5

, ... , , struct ++, class, . , g++ , .

malloc() , . , .

+5

. -POD-. new delete malloc free, . malloc , , , , :

#include <new>
...
run_male_walker_struct *p = (run_male_walker_struct*)
    malloc(sizeof(run_male_walker_struct));
new(p) run_male_walker_struct; // <-- placement-new
...
p->~run_male_walker_struct(); // <-- pseudo destructor call
free(p);

:

run_male_walker_struct *p = new run_male_walker_struct;
...
delete p;

BTW: typedef ++

+3

malloc, ++. NEW - , NEW(), , malloc!!!

NEW - .

, , , :

run_male_walker_struct_t *p = malloc(sizeof(struct run_male_walker_struct));

run_male_walker_struct_t *p = (run_male_walker_struct_t*)malloc(sizeof(struct run_male_walker_struct));

, malloc *.

+2

malloc() , . , , .

, , , . , ( /).

. malloc .

, C ( , C?). , C.

+1

, , std::string , . , , malloc .

:

std::string testString1("babab");
std::string testString2("12345678");
std::string testString3;
std::cout <<" sizeof(testString1)" <<sizeof(testString1) << std::endl;
std::cout <<" sizeof(testString2)" <<sizeof(testString2) << std::endl;
std::cout <<" sizeof(testString3)" <<sizeof(testString3) << std::endl;

:

 sizeof(testString1)8
 sizeof(testString2)8
 sizeof(testString3)8

, :

run_male_walker_struct_t *p = new(struct run_male_walker_struct);

++, malloc .

EDIT: . vs malloc ++: http://www.codeproject.com/KB/tips/newandmalloc.aspx

+1

run_male_walker_struct_t * p = new run_male_walker_struct_t:
+1

, "C struct".

If you mean “a structure valid under the C language,” the answer obviously contains: it contains a data type that is not a valid C, and therefore the structure itself is also invalid.

If you mean the C ++ POD type, then the answer will not be, it is not illegal, but the structure is no longer the POD type (because in order to be POD, all its members must also be POD, but std::stringnot)

+1
source

All Articles