Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to memcpy struct with arrays and some methods?

Tags:

c++

arrays

struct

I am wondering if it is safe to use memcpy on a struct that contain arrays and methods(just some getters and setters since indexing of arrays is unusual and i have to map it somehow). I know that its is safe for PODs and I am unsure if my struct would be considered POD or not?

like image 486
Bartek Boczar Avatar asked Nov 16 '15 21:11

Bartek Boczar


People also ask

When should memcpy be used?

The function memcpy() is used to copy a memory block from one location to another. One is source and another is destination pointed by the pointer. This is declared in “string.

How memcpy works in c++?

memcpy() function is an inbuilt function in C++ STL, which is defined in <cstring> header file. memcpy() function is used to copy blocks of memory. This function is used to copy the number of values from one memory location to another. The result of the function is a binary copy of the data.

What is a memory copy?

Description. In generated code, the Memory Copy block copies variables or data to and from processor memory as you have configured with block parameters. Your model can contain as many of these blocks as you require to manipulate memory on your processor.


1 Answers

You can use memcpy if the struct is TriviallyCopyable.

You can check whether your struct is trivially copyable by using std::is_trivially_copyable.

Also, as pointed out by @JohanLundberg in a comment, the destination address must be 0 modulo std::alignment_of<T>. You can read more about alignment requirements of objects at http://en.cppreference.com/w/cpp/language/object#Alignment.

like image 87
R Sahu Avatar answered Oct 15 '22 17:10

R Sahu