[LC++]Question about ctors and dtors
Chris Vine
chris at cvine.freeserve.co.uk
Fri Apr 5 04:58:04 UTC 2002
On Friday 29 March 2002 4:32 am, Paul M Foster wrote:
> See the following code. When run, the output is only for the test()
> member. There is no output for the ctor and dtor. Why? Surely an object
> of the bogus class is being created?
>
> Paul
>
> ================================ code ============================
>
> #include <vector>
>
> class bogus
> {
> private:
> int x;
> public:
> bogus();
> ~bogus();
> void test();
> };
>
> bogus::bogus()
> {
> cout << "constructing bogus" << endl;
> }
>
> bogus::~bogus()
> {
> cout << "deconstructing bogus" << endl;
> }
>
> void bogus::test()
> {
> cout << "this is a test of bogus" << endl;
> }
>
> int main()
> {
> vector<bogus> mv;
> mv[0].test();
> return 0;
> }
If this is really your code, I am surprised that it produced anything except
a segmentation fault, unless test() is a static member. You are accessing an
object in mv which hasn't been inserted into it.
You should do something like
vector<bogus> mv;
mv.push_back(bogus());
mv[0].test();
return 0;
This will probably call the constructor and destructor of bogus class twice,
unless some behind the scenes reference counting is going on.
Chris.
More information about the tuxCPProgramming
mailing list