naruto90
naruto90

Reputation: 48

static counter value of a class cannot initialize array

A class has a static counter which counts up by one when an object is created. A Get-Method() returns the counter value.
Now I try to initialize a variable in the main function with that counter value, which I will later use for setting the array lengths, but I get the following error on VS 2010:

Blockquote Error 2 error C2466: cannot allocate an array of constant size 42 Error 6 error C2133: 'tInitPositions' : unknown size 43

so why is it not allowed to set an arraylength with a static counter value? A cast to (int const,...) doesn't even solve the problem too

Here is a minimal code for my question:
http://www.fpaste.org/98890/99145533/

Upvotes: 0

Views: 78

Answers (1)

sehe
sehe

Reputation: 393603

To have a compile-time sized array, use

T array_variable[100]; // or some other fixed number of elements

or std::array (see code sample).

To have a runtime sized array, use std::vector:

int const crobotscreated = Robot::GetRobotsCreated();

std::vector<std::thread> evalThreads(crobotscreated);
for (int i = 0; i < crobotscreated; ++i)
{
    evalThreads[i] = std::thread(threadFunction, i);
}

See it Live On Coliru

#include <string>
#include <vector>
#include <thread>

struct TPosition {};

class Robot {
public:
    Robot();
    virtual ~Robot() {};
    TPosition  GetPos() { return mPos; }
    static int mRobotIndex;
    static int GetRobotsCreated();
  private:
    TPosition mPos;

  protected:
    void SetPos();
};

Robot::Robot() {
    mRobotIndex++;
}

int Robot::GetRobotsCreated() {
    return mRobotIndex;
}

int Robot::mRobotIndex=0;

#include <iostream>
#include <mutex>

void threadFunction(int i)
{
    static std::mutex mx;
    std::lock_guard<std::mutex> lk(mx); // take a lock for console output
    std::cout << "Yoohoo from " << i << "\n";
}

int main()
{
    std::array<Robot, 10> robots;

    int const crobotscreated = Robot::GetRobotsCreated();

    std::vector<std::thread> evalThreads(crobotscreated);
    for (int i = 0; i < crobotscreated; ++i)
    {
        evalThreads[i] = std::thread(threadFunction, i);
    }

    for (int i = 0; i < crobotscreated; ++i)
    {
        if (evalThreads[i].joinable())
            evalThreads[i].join();
    }
}

Upvotes: 1

Related Questions