C ++ with fixed sizes and multiple objects of the same type

I was wondering if (besides the obvious syntax differences) there would be a difference in efficiency between having a class containing several instances of an object (of the same type) or an array of a fixed size of objects of this type.

In code:

struct A {
  double x;
  double y;
  double z;
};

struct B {
  double xvec[3];
};

In fact, I would use boost :: arrays, which are the best C ++ alternative for C-style arrays.

I mainly deal with the construction / destruction and reading / writing of such doubles, because these classes are often created only to call one of their member functions once.

Thanks for your help / suggestions.

+5
source share
6 answers

, . , , .

, , , :

for (int i = 0; i < 3; i++)
    dosomething(xvec[i]);

:

dosomething(x);
dosomething(y);
dosomething(z);

, . , ; , , I-.

- :

for (int i = 0; i < 3; i++) {
    int *r;
    switch(i) {
        case 0: r = &x; break;
        case 1: r = &y; break;
        case 1: r = &z; break;
    }
    dosomething(*r); // assume this is some big inlined code
}

i-cache, . .

, , , :

xvec[0] = xvec[1] + 1;
dosomething(xvec[1]);

xvec [0] xvec [1] , , xvec [1] , . , , , xvec [0] xvec [1] . .

, , . , .

, , xvec . , , , , -.

+8

MV++ 2010 / POD, . / , . .

, : , , - ?

, , , , .

+5

, , :

struct Foo
{
    union
    {
        struct
        {
            double x;
            double y;
            double z;
        } xyz;
        double arr[3];
    };
};

int main()
{
    Foo a;
    a.xyz.x = 42;
    std::cout << a.arr[0] << std::endl;
}

, xyz.

+2

. , " ": / ( )

  • (?) , ( - , , )

( /) C-, , / .

- , ++ == STL-, , nuthin ':)

+1

. . paticular .

+1

, ++, , , - .

The real answer, of course, creates a test case and measures.

-1
source

All Articles