Re: Class Destroys itself straight away!
- From: "Alex Blekhman" <tkfx.REMOVE@xxxxxxxxx>
- Date: Sat, 26 Jan 2008 19:34:27 +0200
"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
.
- References:
- Class Destroys itself straight away!
- From: Gerry Hickman
- Class Destroys itself straight away!
- Prev by Date: Class Destroys itself straight away!
- Next by Date: Re: Class Destroys itself straight away!
- Previous by thread: Class Destroys itself straight away!
- Next by thread: Re: Class Destroys itself straight away!
- Index(es):
Relevant Pages
|