Dear Jim,
Thank you very much. Your explanation is right. It was not the
reference or pointer that caused the problem but the place your pointed
out.
The vector constructor does create a temporary object and copy it to
all the vector members and destroy it. I put some cout statements in
the constructor, copy constructor and destructor and got relevant
information.
I said that when I put nothing in the copy constructor it still works.
I was wrong. It only works when I don't access anything within the
object, otherwise it causes segmentation error because all its members
will have no valid value if nothing was done in the copy constructor.
I attached my updated program below for context and left some comments.
Now I don't need your technique of pointers. I will keep it in mind
in case needed. Thanks a lot.
Regards,
Brian
Jim Langston wrote:
>
Please don't top post. Please supply more context from previous post.
int main()
{
ArrayWrap dum;
ArrayWrap & rdum = dum;
vector<ArrayWrapdummy(10);
// I believe the previous line is your problem
vector<ArrayWrap& refdummy = dummy;
cout << "done" << endl;
return 0;
}
Vectors tend to be a pain this way. It seems (to me) that when you put an
item into a vector it first creates it into a temporary, then copies the
temporary into the vector. So when the temporary gets destroyed, it runs
the destructor and you're hozed.
I've run into this problem before with classes that are not copyable (
unique objects loaded that can't be copied, or are just a waste of time to
copy). The way I've solved this is to make a private copy constructor (so
it *can't* be copied) then to make my vector into pointers.
vector<ArrayWrap*dummy;
for ( i = 0; i < 10; i++ )
ArrayWrap.push_back( new ArrayWrap );
// code
for ( vector<ArrayWrap>::iterator it = ArrayWrap.begin(); it !=
ArrayWrap.end(); ++it )
delete (*it); // double check syntax of this
------------------------------------------------------------------------------------------------------
#include <iostream>
#include <vector>
using namespace std;
class ArrayWrap
{
public:
char * pt_ch;
ArrayWrap()
{
pt_ch = new char[100];
pt_ch[0] = 'b';
cout << "create dummy" << endl;
}
ArrayWrap(const ArrayWrap & AnArray)
{
pt_ch = new char[100]; // this made copy's pt_ch valid
pt_ch[0] = AnArray.pt_ch[0]; // this assigned values to
// the copy.
cout << "copy dummy" << endl;
}
~ArrayWrap()
{
delete[] pt_ch;
cout << "destruct dummy" << endl;
}
int print()
{
cout << pt_ch[0] << endl;
return 1;
}
};
int main()
{
ArrayWrap dum;
vector<ArrayWrapdummy(5); // copy constructor
// is needed here, otherwise
// pt_ch of dummy[i] points
// to destroyed temporary
// ArrayWrap object
vector<ArrayWrap& refdummy = dummy;
vector<ArrayWrap* pdummy;
dummy[0].print(); // this will cause segmentation
// error if copy constructors
// first two statements is omitted
cout << "done" << endl;
return 0;
}