1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
struct object
{
virtual ~object() {} // a virtual destructor is required
// ...
};
struct vect { vect( double x, double y, double z ) { /* ... */ } /* ... */ };
struct sphere : object
{
sphere( vect v, double r ) : location(v), radius(r) { /* ... */ }
sphere( double x, double y, double z, double r ) : location(x,y,z), radius(r) { /* ... */ }
// ...
private:
vect location ;
double radius ;
};
int main()
{
{
// C++11
std::vector< std::unique_ptr<object> > scene_objects ; // #include <memory>
// http://en.cppreference.com/w/cpp/memory/unique_ptr
scene_objects.emplace_back( new sphere( 0, 0, 0, 0.5 ) ) ;
scene_objects.emplace_back( new sphere( 0, 1, 0, 0.5 ) ) ;
// etc...
// use scene_objects ...
}
{
// C++98
std::vector< object* > scene_objects ;
scene_objects.push_back( new sphere( 0, 0, 0, 0.5 ) ) ;
scene_objects.push_back( new sphere( 0, 1, 0, 0.5 ) ) ;
// etc...
// use scene_objects ...
// clean up
for( std::size_t i = 0 ; i < scene_objects.size() ; ++i )
delete scene_objects[i] ;
}
}
|