Is this code look weird?

I wrote a class and use the vector<> container as members of this class. I have never see this code style before, I'm feeling a bit weird about that. But it really works(in my vc++ compiler).
By using this style, is there any hidden troubles that may happen?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Grid
{
public:
	Grid() { gunit=NULL; };//
	Grid(int dim):n(dim),cnt(0),gunit(new GridUnit[n*n]) ,adj(new  vector<Node>[dim*dim])
	{   
	}
	
	~Grid( )
	{	delete []gunit; delete []adj; }

	void InitialGrid( );
	//......other function

protected:
public:
	int  n;					  //dimension
	int  cnt,//count the number of gridpoints have been initialized
	GridUnit* gunit;      //GridUnit is anthoer class ,array for gridpoints 
	vector<Node>* adj;     //??
	vector<Node>::iterator it;//??
};
Nothing weird. It is actually very correct to use the initializer list as much as possible -- it generates much cleaner code.

You need to be careful, however, not to dispose of memory before you are done with it by inadvertently using the default copy constructor -- when the copy is destroyed your original will also have its memory freed (in the destructor) -- creating dangling pointers and unexplained segfaults. (In other words, make sure you write a copy constructor.)

Hope this helps.
Well, it doesn't look like it would compile. Shouldn't the [] be () in the initializer list? Also, I'd either use n or dim but using one for the first array and the other for the next looks kind of confusing. It isn't a big deal but it looks confusing.

Also, I don't normally make iterators class attributes. I'm not saying that it is wrong, but it looks kind of weird. What happens if the vector's contents change? iterators can be invalidated when you perform certain operations. You'll have to be careful managing that as a class attribute. I usually just create iterators within local functions as I need them.
The only uncompilable is the comma on line 18 (instead of a semicolon).

The [] is correct. (The new operator takes square brackets to indicate array size.)
I agree that you should use 'dim' instead of 'n' when initializing 'gunit'.

Ditto on the iterator.
EDITED: Oh, I see what you are saying Duoas. As it is coded, an array of vectors the size of dim*dim is constructed and each vector is default constructed, right? I think that is the part that trips me up because that isn't what I was expecting. On the other hand, why would someone just a pointer to a single vector and use operator new to build it? The () would be used to construct a single vector. I've never seen anyone try to build an array of vectors like that. Usually, I see the vector of vectors when someone wants a multi-dimensional vector like so:

std::vector<std::vector<type> > mdVectorInst;
Last edited on
Yeah, it's odd. The OP will have to mess around with it to find out what works and doesn't. :-)
Topic archived. No new replies allowed.