Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ string in C struct, is it illegal?

Tags:

c++

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? As the string is a class, it's size can't be determined by sizeof().

like image 335
Bin Chen Avatar asked Sep 30 '10 05:09

Bin Chen


People also ask

Can you put a string in a struct?

The answer is yes unless you are using an obsolete compiler that does not support initialization of structures with string class members. Make sure that the structure definition has access to the std namespace. You can do this by moving the using directive so that it is above the structure definition.

Can you use std :: string in C?

A std::string_view can refer to both a C++ string or a C-string. All that std::string_view needs to store is a pointer to the character sequence and a length. std::string_view provides the same API that std::string does, so it is a perfect match for C-style string literals.

How do you declare a string in structure?

Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.


1 Answers

This is illegal, but not for the reasons you're thinking.

The difference between std::malloc()/std::free() and new/delete is that the latter will call constructors/destructors, while the former won't. The expression

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

will return a blob of uninitialized memory on which no constructor is called. You shouldn't touch it with a ten foot pole - except for invoking a constructor on it:

run_male_walker_struct* pw = new(p) run_male_walker_struct;

If you do this, you will have to do the reverse, too:

pw->~run_male_walker_struct();

before you free the memory:

std::free(p);

However, that leaves the question why you want to do that.
The only reason to do this should be when you want to separate memory allocation from construction (like, for example, in a pool allocator). But if you need that, it's best hidden behind some interface. A natural one would be overloading new and delete per class. Also, std::vector does this internally.

like image 193
sbi Avatar answered Sep 17 '22 18:09

sbi