Setting a value of nested class in shared_ptr

I am trying to use a vector of shared_ptr (boost lib) that points to a class with a nested class (hope I got all that right). So far I have:
1
2
typedef boost::shared_ptr<Site> siteptr;
std::vector<siteptr> sites;


and when I go to initialize the class I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
while (list>>str) {
	cstr = new char [str.size()+1];
	strcpy (cstr, str.c_str());
	latlonvar[1] = atof(cstr);
	list>>str;
	cstr = new char [str.size()+1];
	strcpy (cstr, str.c_str());
	latlonvar[2] = atof(cstr);
	list>>str;
	cstr = new char [str.size()+1];
	strcpy (cstr, str.c_str());
	latlonvar[3] = atof(cstr);
		
	xy = ll2lcc(1000.0,latlonvar[1], latlonvar[2]);
	subx = xy[1] - subd[1];
	suby = xy[2] - subd[2];
	nsites++;
		
	siteptr site_ptr( new Site);
	sites.push_back(site_ptr);
}


and just for more info, my header is:
1
2
3
4
5
6
7
8
9
10
11
12
class Point {
	public:
	int x;
	int y;
};	

class Site {
	public:
	Point coord;
	int sitenbr;
	int refcnt;
};


The last two lines are what my question is about. I want to set sites->coord.x but have no clue how to do this. I get that siteptr site_ptr( new Site); is creating a shared pointer that points to the class Site but within new Site do i need to set the value of sites->coord.x = subx like this:
 
siteptr site_ptr( new Site(sites->coord.x = subx);


or maybe:
 
siteptr site_ptr( new Site(this->coord.x = subx);

As you can probably tell I'm really not sure. Or can I initialize the class and set the value later?

FYI, I'm new to c++ so be gentle.
¿Do you know another language? You are confusing classes with objects.
1
2
siteptr site_ptr(new SIte);
site_ptr->coord.x = subx;
But, ¿do you really need a shared pointer there?


Also
1
2
3
4
5
6
/*
	cstr = new char [str.size()+1];
	strcpy (cstr, str.c_str());
	latlonvar[1] = atof(cstr);
*/
	latlonvar[1] = atof(str.c_str());
You need to write constructors for your classes. e.g.

1
2
3
4
5
6
7
8
class Point {
public:
   Point(int setx,int sety)
    :  x(setx), y(sety) { }
private:
  int x;
  int y;
};


I have put you variables in a private section since this is the normal thing to do (but not a requirement)
The constructor I have written uses an initialisation list (and has an empty body)

With this constructor you can now create a point like this
 
Point p(4,5); // sets x to 4 and y to 5 


or to use a shared_ptr you can use it like this
 
boost::shared_ptr<Point> p(new Point(4,5));



@deadpickle

(aside)

if you're doing the allocation and copy just to you can use atof, you're doing too much work. Instead of

1
2
3
	cstr = new char [str.size()+1];
	strcpy (cstr, str.c_str());
	latlonvar[1] = atof(cstr);


just use

latlonvar[1] = atof(str.c_str());

Also note that you're leaking memory as you don't delete [] cstr; after you've finished using the previous string.

Andy

Last edited on
Topic archived. No new replies allowed.