mardi 21 avril 2015

c++11 variable sized array class attribute [duplicate]

This question already has an answer here:

Edit 2 Please ignore the duplicate specification...this is NOT a duplicate question, and the "other" answer does not answer my question...there's not even a class involved in the other question.

Edit Before you downvote this, as I know the title of this is stupid, please first read through the whole answer. I am asking about what the real, underlying reason is that this does not want to compile. So it's not a complete noob question.

In C++11, the variable sized array constraint seems to have been relaxed quite a bit, since

int main()
{
    int size;
    double data [size];

    return 0;
}

compiles, but on the other hand, in a class declaration

#ifndef PSO_H
#define PSO_H
#include <string>

class PSO
{
    private:
        static double * data;
        static int len;
        static int dim;
        double position [dim];
        double velocity [dim];

        double get_min();
        double get_max();

    public:
        PSO();
        PSO(int, double [], int);
        PSO(int dimensions, std::string file_name);
        void update_position();
        void update_velocity(double pers_best [], double glob_best []);
        void update(double, double);
};
#endif

the compiler complains about the dim variable that I use to specify the size of the position and velocity arrays. Why is that?

I read something in this answer http://ift.tt/1Gg9sDP that class definitions need to be unique, and that the "rule will be broken" if it allowed "in-class definition of entities that needed to be stored in memory in objects" (maybe I know what that means...maybe not). The answer I mentioned above also has an addition for C++11, since most of it is on C++03 (which I know does not support variable sized arrays), but the C++11 answer, which consists mostly of an extract from the C++11 reference by Bjarne Stroustrup, is in a language I don't quite understand.

I realize I should probably be using std::vector for this, or if not that, the new operator with a proper double * variable, but I am just trying to understand why this is not working (in fact, in a little test that I did on how efficiently the code works with arrays, I found that, all other things constant, the processor will take much more time to work with a std::vector array than with a pointer, and declaring the array with square braces, like I defined position and velocity in the code above, actually is the most efficient (in my case). I sometimes work with large amounts of data, so processing efficiency is a big deal for me...but anyway, why does the first code snippet, but not the second, compile?

Aucun commentaire:

Enregistrer un commentaire