trouble with new keyword

Started by
4 comments, last by smart_idiot 18 years, 8 months ago
Hi. I'm currently implementing a very basic particle system. Particles are represented by the CParticle class. Particles belong to a CParticleSystem and are stored in a single pool, so no creating/destroying particles is needed while the system is running. When a particlesystem is created it will create int m_numparticles of particles. The particles are stored in a plain array as I wont need to resize it constantly. I've tried creating the array like this:

    m_particles = NULL;

    // create array of m_numparticles. 'this'is a pointer to the parentsystem.
    // CParticle(CParticleSystem *a_system) is a constructor of CParticle.
    m_particles = new CParticle(this) [m_numparticles]; 
but it doesn't work. The compiler gives me this error. error: expected ';' before '[' token Does anyone know what is wrong?
Advertisement
m_particles = new CParticle[m_numparticles]; for(int i = 0; i < m_numparticles; i++){  m_particles = new CParticle(this);}


later edit: assuming CParticle** m_particles [wink]
You can't pass arguments to the constructor of elements of an array being created dynamically. Consider using std::vector which will allow you to specify an object to copy construct the elements from.
To be a little more explicit:

std::vector<CParticle> m_particles(m_numparticles, CParticle(this));// the temporary, stack-allocated CParticle is copy-constructed to each// element of the vector. The vector "knows" its size, so m_numparticles// will become redundant. You will of course need a proper copy constructor// and destructor (and therefore assignment operator) for the CParticle -// depending on what exactly is in there, the defaults may be ok.
I guess I'll use werekarg's approach, as I don't want to use a vector for an array that will only change it's size once. Thanks all of you though.
That's a weak argument. Using a vector is just as efficient as using an array created with new. Sure, it contains a few extra bytes used for it's internal book keeping, but you dragging around that m_numparticles variable isn't a whole lot better.
Chess is played by three people. Two people play the game; the third provides moral support for the pawns. The object of the game is to kill your opponent by flinging captured pieces at his head. Since the only piece that can be killed is a pawn, the two armies agree to meet in a pawn-infested area (or even a pawn shop) and kill as many pawns as possible in the crossfire. If the game goes on for an hour, one player may legally attempt to gouge out the other player's eyes with his King.

This topic is closed to new replies.

Advertisement