std::complex

M

Marcin Kalicinski

Hi,

I found out that default constructor of std::complex class initializes the
value to (0,0). I wonder why is it so?

Because of this, the code below is about two times slower than it could be
if the default constructor left the values uninitialized.

void f()
{
using namespace std;
complex c[100];
for (int i = 0; i < 100; ++i) c = complex(1, 0);
}

Values of built in types work perfectly without zero initialization, so why
make complex different and cause additional learning trouble?

Best regards,
Marcin
 
J

John Harrison

Marcin Kalicinski said:
Hi,

I found out that default constructor of std::complex class initializes the
value to (0,0). I wonder why is it so?

Because of this, the code below is about two times slower than it could be
if the default constructor left the values uninitialized.

How have you managed to time that, or is it just a guess?
void f()
{
using namespace std;
complex c[100];
for (int i = 0; i < 100; ++i) c = complex(1, 0);
}

Values of built in types work perfectly without zero initialization, so
why make complex different and cause additional learning trouble?


Most people would say that uninitialised variables are what causes learning
trouble, not to mention bugs.

How about rewriting your code like this?

#include <vector>
#include <complex>

void f()
{
using namespace std;
vector<complex> c(100, complex(1, 0));
}

john
 
M

Marcin Kalicinski

I found out that default constructor of std::complex class initializes
How have you managed to time that, or is it just a guess?

I have generated an assembly listing on MSVC .NET 2003 all optimizations
enabled. Here's the function:

#include <complex>
std::complex<float> f()
{
std::complex<float> c[100];
for (int i = 0; i < 100; ++i)
c = std::complex<float>(1, 0);
return c[50];
}

Below is a relevant part of assembly listing for the function f. Note the
loop that is created by line #5 (the definition of the array):

; 5 : std::complex<float> c[100];

lea eax, DWORD PTR _c$[esp+800]
mov ecx, 100 ; 00000064H
xor edx, edx
$L11604:
mov DWORD PTR [eax], edx
mov DWORD PTR [eax+4], edx
add eax, 8
sub ecx, 1
jne SHORT $L11604

; 6 : for (int i = 0; i < 100; ++i)

xor eax, eax
mov ecx, 1065353216 ; 3f800000H
$L10133:

; 7 : c = std::complex<float>(1, 0);

mov DWORD PTR _c$[esp+eax*8+800], ecx
mov DWORD PTR _c$[esp+eax*8+804], edx
add eax, 1
cmp eax, 100 ; 00000064H
jl SHORT $L10133


Best regards,
Marcin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,183
Messages
2,570,970
Members
47,525
Latest member
emmawilsonpark

Latest Threads

Top