c++ - How can I add and initialize objects in a vector without having the destructor for the existing objects called? -


i working homework assignment , have come across problem when added destructor class.

from assignment:

the class have destructor displays message indicating object has "gone out of scope".

i've implemented in rectangle class outputting ofstream object:

rectangle::~rectangle() {     rectoutput << "object length " << length << " , width " << width << " out of scope." << std::endl; } 

the problem i'm running that, put these objects vector make easy output table. looked until added destructor. due way vectors copy data new internal array , delete old array increase size, destructor called , message output several times in creation of objects.

part of constraints of homework had initialize of objects values. choice use vector own. here code of initalization of objects:

std::vector <rectangle> rectangles;  //initialize of our rectangle objects within our vector rectangles.push_back(rectangle()); rectangles.push_back(rectangle(7.1, 3.2)); rectangles.push_back(rectangle(6.3)); rectangles.push_back(rectangle(21.0, 21.0)); rectangles.push_back(rectangle(rectangles[1])); 

and here output being produced this:

object length 1 , width 1 out of scope.
object length 1 , width 1 out of scope.
object length 7.1 , width 3.2 out of scope.
object length 1 , width 1 out of scope.
object length 7.1 , width 3.2 out of scope.
object length 6.3 , width 1 out of scope.
value of 21 invalid. values must greater 0.0 , less or equal 20.0. default of 1.0 used.
value of 21 invalid. values must greater 0.0 , less or equal 20.0. default of 1.0 used.
object length 1 , width 1 out of scope.
object length 7.1 , width 3.2 out of scope.
object length 6.3 , width 1 out of scope.
object length 1 , width 1 out of scope.
object length 1 , width 1 out of scope.
object length 7.1 , width 3.2 out of scope.
object length 6.3 , width 1 out of scope.
object length 1 , width 1 out of scope.
object length 7.1 , width 3.2 out of scope.

how can initialize these objects in vector without having destructor being called repeatedly this? tried start off std::vector <rectangle> rectangles(5);, seems call default constructor 5 times, filling vector 5 default rectangle objects , when add same effect seen, except destructing default objects.

use rectangles.emplace_back() instead of rectangles.push_back() , still need reserve mentioned sam varshavchik


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -