Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Solving the "constructor" problem in C++

Author: Steffen Jakob

Date: 12:33:23 06/12/02

Go up one level in this thread


On June 12, 2002 at 15:09:30, Russell Reagan wrote:

>After making my decision to use C++ instead of C, I thought I had most of the
>drawbacks covered, or at least I was content with the drawbacks that I hadn't
>solved. One drawback that I didn't think of was that the constructors for an
>object would run even if they did nothing. So when I create an array of moves in
>my alpha-beta function, the constructor will run many times, and when done
>recursively, that's a bad thing.
>
>I saw several people post workarounds using malloc() or other slightly cryptic
>hacks that I'd rather avoid, and these are the ideas I've come up with so far to
>try and solve this problem.
>
>My first idea was to use an STL vector instead of an array, and since a vector
>wouldn't actually contain any objects when it's initialized, the constructors
>shouldn't run right? My solution would require that the objects had proper
>constructors so that I could do something like the following:
>
>vector<Move> legalMoves;
>legalMoves.push_back( Move(from,to) );
>
>That would allow me to get the correct move into the vector without having to
>"waste" constructor calls.
>
>My second idea was to use a struct instead of a class for things that will be
>created on the fly like Move. If I did this, I could still add methods to the
>Move struct in C++, but as far as I know I don't have to write a constructor,
>and then I could only initialize the data manually.
>
>So will either of these solutions work, or does anyone have any other
>suggestions?

I think I dont understand. Do you think in the following code the default ctor
of class C would cost time? You c++ compiler should optimize this call away (at
leas g++ 3.0.2 which i have installed here does so).

class C {
public:
	C() { /* do nothing and leave n uninitialized. */ }
	C(int _n) : n(_n) { }

	void set(int _n) { n = _n; }
	const int &get() const { return n; }

private:
	int n;
};

int main(int argc, char **argv) {
	C c; // triggers the default ctor
	return c.get(); // do something with c
}

Greetings,
Steffen.



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.