Cleanest way to copy a constant size array in c++11

I often find myself wanting to copy the contents of arrays that have a constant size, I usually just write something along the lines of:

float a[4] = {0,1,2,3};
float b[4];

for(int i=0; i<4; i++){
    b[i]=a[i];
}

As of lately, I am writing a linear calculus library for educational purposes, and I was wondering if there was a better way to do it.

The first thing that came to my mind, was using memcpy:

memcpy(b, a, sizeof(float) * 4);

But this seems very c-like and error prone to me. I like having my errors at compile time, and this can get ugly for data types with non-trivial copy constructors, or if I forget to multiply with sizeof(datatype).

Since I am writing a math library that I am going to use intensively, performance is very important to me. Are the compilers today smart enough to understand that the first example is just copying a chunk of memory and optimize it to be as efficient as the second solution?

Perhaps there is a function in the standard library that can help me? Something new in c++11? Or should I just create a macro or a template function?

Answers


If you use std::array instead of a built-in array (which you should), it becomes very simple. Copying an array is then the same as copying any other object.

std::array<float,4> a = {0,1,2,3};
std::array<float,4> b = a;

Need Your Help

How to add special characters to tooltip using code behind?

c# asp.net devexpress

I am adding a tooltip to an aspxButtonEdit in code behind. This works, but special characters like e.g. &darr; are not rendered, instead the text is rendered. I tried to set EncodeHtml (true/ false)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.