Re: Class Destroys itself straight away!

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



"Gerry Hickman" wrote:

I have a Class who's constructor accepts an STL wstring, but it
seems to kill itself before it can be used. If I initialize with
int, it works as expected. Here's the sample code and the
output. Note the Destructor is firing twice.

#include "stdafx.h"
using namespace std;

class MyClass
{
public:
MyClass(wstring);
~MyClass(void);
void SayHello(void);
};

int _tmain(int argc, _TCHAR* argv[])
{
wstring wsInput = _T("Passed in String");
MyClass mc = MyClass(wsInput);
// Class kills itself here!

No, a temporary copy is destroyed. The `mc' object is copy
constructed and alive until the end of the scope (i.e., _tmain
function).

Declare a copy constructor for `MyClass', then you'll see that
creation and destruction are symmetric:

class MyClass
{
public:
MyClass(const MyClass& other);
...
};

MyClass::MyClass(const MyClass& other)
{
wcout << "Copy constructing Class" << endl;
}


Also, MyClass's constructor makes redundant copy of its parameter
since `wsNewString' is passed by value. Pass it by reference to
avoid unnecessary copy:

MyClass::MyClass(const wstring& wsNewString)
{
...
}


Alex


.



Relevant Pages

  • Re: Class Destroys itself straight away!
    ... I have a Class who's constructor accepts an STL wstring, but it seems to kill itself before it can be used. ... MyClass mc = MyClass; ... void MyClass::SayHello ...
    (microsoft.public.vc.language)
  • Re: Author of Visual C++ 2005 STL ???
    ... static int count; ... to the copy constructor, ... so I think that only one copy ctor is required for the ... MyClass copy ctor ...
    (microsoft.public.vc.mfc)
  • Re: Singleton
    ... (new myClass()) can not be null|false|undefined.. ... As you are using a constructor to create this object instance it would ... be possible to define the created object's - constructor property on the ...
    (comp.lang.javascript)
  • Re: Copy Constructor to load List
    ... The second loop is excessive. ... there is no need to use the extra copy constructor. ... > MyClass mc = new MyClass ... > mc.b = loopcount; ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Is it good programming to set instance in class without using C-tor
    ... I have a class definition called MyClass see below. ... I create an instance of this class MyClass ... the question of what arguments should go on the constructor is ... your client has to test before they try to use an object instance. ...
    (microsoft.public.dotnet.languages.csharp)