DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   vector trouble (http://www.daniweb.com/forums/thread158145.html)

arreyes Nov 18th, 2008 6:04 pm
vector trouble
 
If you make a vector of a class of no designated size, as you reserve spaces inside the vector will it just make a default instance from the constructor?

Lerner Nov 18th, 2008 6:30 pm
Re: vector trouble
 
Probably, you can check it out pretty easy.

Be careful of the word size. size is frequently used to indicate the actual number of elements currently in the vector as opposed to the number of elements for which space is allocated for vector use, which might be called capacity or size.

ArkM Nov 18th, 2008 7:32 pm
Re: vector trouble
 
Fortunately you CAN'T invent a "class of no designated size" in C++. For every class its objects have fixed and defined size (remember operator sizeof).
If you mean a class with dynamically allocated members then it's a problem of this class constructor, not a vector container. That's why class constructors were invented.

arreyes Nov 18th, 2008 7:54 pm
Re: vector trouble
 
i meant i created a vector of unspecified size. but when I reserve a spot then try to alter the instance an error pops up and I get a window telling me that the program has to close because it has run into an error. I just don't know what is going on.

MosaicFuneral Nov 18th, 2008 10:55 pm
Re: vector trouble
 
Post code.

Manutebecker Nov 18th, 2008 11:23 pm
Re: vector trouble
 
Your question is difficult to understand, but if you mean will it construct what you have in a default constructor to each instance of said class, then yes it should.

ArkM Nov 19th, 2008 2:09 am
Re: vector trouble
 
If you are using std::vector class then probable causes are:
1. You reserve vector size then try to access its elements, but reserve member function does not construct vector elements. You need resize (not reserve) vector if you want to access new elements immediatly.
2. Your class has bad default constructor (constructor without arguments). For example:
class Bad {
    Bad() {} // Forgot to initialize pDynArr with 0.
    Bad(const char* p, int n) {
        pDynArr = new char[n];
    }
    ~Bad() { delete [] pDynArr;
private:
    char* pDynArr;
};
...
std::vector<Bad> troubles;
...
troubles.resize(10);
...
New Bad objects created after vector<Bad>::resize(k) are true bad. There are garbage values of pDynArr member in all 10 vector elements. The destructor of troubles calls Bad destructor for every 10 elements, the last one call delete [] pDynArr for undefined pointer.

Follow MosaicFuneral's advice ;)...


All times are GMT -4. The time now is 6:35 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC