I'm new to C++ and I'm trying to get my head round how memory is managed.
Take a look at this:-

Class CMyClass
{
private:
char * m_str;
public:
CMyClass(char * str)
{
m_str = str;
}
~CMyClass(void)
{
// Do I need to anything with m_str
}
}

function a()
{
CMyClass ThingInA;
ThingInA = b();
}

function b()
{
CMyClass ThingInB("Hello World");
return ThingInB;
}

If I understand things correctly both ThingInA and ThingInB are allocated
off the stack. return in functon b()copies the contents fo ThingInB to
ThingInA.

Has a constructor been executed for ThingInA before b is executed? There
isn't one defined for void.
When b returns does a destructor happen for the contents of ThingInA first?
Where is the memory to store the "Hello World" string allocated? I guess
it's in the module somewhere and is treated as const, in which case I should
be using const char above right?

TIA for patient answers,

Anthony.

Re: C++ 101 dumb question by SvenC

SvenC
Thu Jun 21 05:14:59 CDT 2007

Hi,

Anthony Jones wrote:
> I'm new to C++ and I'm trying to get my head round how memory is
> managed. Take a look at this:-
>
> Class CMyClass
> {
> private:
> char * m_str;

Try to avoid using raw pointers. For strings either use std::string or
CString when you are in an MFC/ATL project.

> public:
> CMyClass(char * str)

Make this "const char* str" to make clear that str is not changed inside of
the constructor.

With std::string and CString you can safely write m_str = str;


> {
> m_str = str;
> }
> ~CMyClass(void)
> {
> // Do I need to anything with m_str
> }

With std::string and CString you need no cleanup here

> function a()

You maybe wanted "void a()"

> {
> CMyClass ThingInA;
> ThingInA = b();
> }
>
> function b()

You could do "CMyClass b()"

> {
> CMyClass ThingInB("Hello World");
> return ThingInB;
> }

Please start with a beginners book on C++ as the above is more JavaScript
than C++.

--
SvenC


Re: C++ 101 dumb question by MrAsm

MrAsm
Thu Jun 21 05:27:24 CDT 2007

On Thu, 21 Jun 2007 10:29:38 +0100, "Anthony Jones"
<Ant@yadayadayada.com> wrote:


>Class CMyClass
>{
>private:
> char * m_str;
>public:
> CMyClass(char * str)
> {
> m_str = str;
> }
> ~CMyClass(void)
> {
> // Do I need to anything with m_str
> }
>}

In addition to what SvenC wrote, I'd like to add that, if you use raw
pointers (like tha 'char *'), you also need to implement a copy
constructor and operator= in your class, e.g.:

// Copy ctor
CMyClass( const CMyClass & );

// operator=
CMyClass & operator=( const CMyClass & );

and maybe also define your destructor to be 'virtual', to be safe e.g.
with inheritance:

virtual ~CMyClass();

C++ has several subtle things, that you don't find in C# or
Javascript... You'd better taking a good C++ book and study it and
*write* lots of code (and debug it, to learn a lot also from your
errors).

I wish you a great experience learning C++!

MrAsm

Re: C++ 101 dumb question by David

David
Thu Jun 21 05:38:07 CDT 2007


"Anthony Jones" <Ant@yadayadayada.com> wrote in message
news:uE2cxa%23sHHA.1168@TK2MSFTNGP02.phx.gbl..

> I'm new to C++ and I'm trying to get my head round how memory is managed.
> Take a look at this:-
>
> Class CMyClass
> {
> private:
> char * m_str;
> public:
> CMyClass(char * str)
> {
> m_str = str;
> }
> ~CMyClass(void)
> {
> // Do I need to anything with m_str
> }
> }
>
> function a()
> {
> CMyClass ThingInA;
> ThingInA = b();
> }
>
> function b()
> {
> CMyClass ThingInB("Hello World");
> return ThingInB;
> }

Have you tried compiling this?

What do you mean by "function"?

Apart from that, a() would not compile as there is no constructor for
CMyClass which takes no arguments.

And you need to understand that copying a pointer is not the same as copying
the thing it points to (and/or that the default copy constructor of CMyClass
copies a pointer.)

Dave
--
David Webber
Author of 'Mozart the Music Processor'
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm


Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 06:25:44 CDT 2007


"MrAsm" <mrasm@usa.com> wrote in message
news:5akk7311l2bch65l9s6ig363t9dmsgsp9e@4ax.com...
> On Thu, 21 Jun 2007 10:29:38 +0100, "Anthony Jones"
> <Ant@yadayadayada.com> wrote:
>
>
> >Class CMyClass
> >{
> >private:
> > char * m_str;
> >public:
> > CMyClass(char * str)
> > {
> > m_str = str;
> > }
> > ~CMyClass(void)
> > {
> > // Do I need to anything with m_str
> > }
> >}
>
> In addition to what SvenC wrote, I'd like to add that, if you use raw
> pointers (like tha 'char *'), you also need to implement a copy
> constructor and operator= in your class, e.g.:
>
> // Copy ctor
> CMyClass( const CMyClass & );
>
> // operator=
> CMyClass & operator=( const CMyClass & );
>
> and maybe also define your destructor to be 'virtual', to be safe e.g.
> with inheritance:
>
> virtual ~CMyClass();
>
> C++ has several subtle things, that you don't find in C# or
> Javascript... You'd better taking a good C++ book and study it and
> *write* lots of code (and debug it, to learn a lot also from your
> errors).
>
> I wish you a great experience learning C++!
>
> MrAsm

Thanks guys for your input. I had my suspicion that the answer is
ultimately 'go read a book' however that (along with using the Web) is what
I am doing. As you've guessed I spend most of my time writing Javascript
and I will continue to do so. However I'm also required to maintain and
developer an ISAPI filter which up to now has be fairly basic but is getting
more complex.

I dumbed down the example in a (failed) attempt to focus on a particular
area which so far in my studies seems somewhat ambigous. I'm hoping that
some one can say something in such that the penny will drop. Let me bring
up the detail a little (and ditch the distracting string stuff in real code
I'm using CString).

My main focus is the behaviour of the return of a function. Nothing I've
read so far explains step by step what actually happens when returning a
object. Here is better example:-

Crypto.h
=======
class Crypto
{
public:
Crypto();
~Crypto();
//Public methods here
private:
HCRYPTPROV m_hProv;
};

Crypto.cpp
=========
#include "StdAfx.h"
#include "Crypto.h"

Crypto::Crypto(void)
{
m_hProv = 0;
CryptAcquireContext(&m_hProv, 0, 0, PROV_RSA_FULL,
CRYPT_MACHINE_KEYSET | CRYPT_SILENT |
CRYPT_VERIFYCONTEXT);
};
Crypto::~Crypto(void)
{
if (m_hProv != 0) CryptReleaseContext(m_hProv, 0);
};
// Other method implementations here


Now I use this class like this:-

void a()
{
Crypto oCryptoInA;
oCryptoInA = b();
}

Crypto b()
{
Crypto oCryptoInB;
return oCryptoInB;
}

Now at guess the sequence of events on return in b is:-

Destructor of Crypto is called where this is oCryptoInA.

Data members at oCryptoInB are copied in to oCryptoInA (this is a simple mem
copy since no operator= is defined).

Destructor of Crypto is called where this is oCryptoInB.

This leaves m_hProv in oCryptoInA holding a handle that has now been
released.

Have I got the sequence right? What represents a good solution?

If I were to substitute the simple handle of m_hCrypto with a COM Smart
pointer would I be the same sort of bother. That is without an
implementation of operator= the smart point will not track the correct
number of references and destory the object prematurely.






Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 06:43:15 CDT 2007


"David Webber" <dave@musical-dot-demon-dot-co.uk> wrote in message
news:eNoPTB$sHHA.508@TK2MSFTNGP02.phx.gbl...
>
> "Anthony Jones" <Ant@yadayadayada.com> wrote in message
> news:uE2cxa%23sHHA.1168@TK2MSFTNGP02.phx.gbl..
>
> > I'm new to C++ and I'm trying to get my head round how memory is
managed.
> > Take a look at this:-
> >
> > Class CMyClass
> > {
> > private:
> > char * m_str;
> > public:
> > CMyClass(char * str)
> > {
> > m_str = str;
> > }
> > ~CMyClass(void)
> > {
> > // Do I need to anything with m_str
> > }
> > }
> >
> > function a()
> > {
> > CMyClass ThingInA;
> > ThingInA = b();
> > }
> >
> > function b()
> > {
> > CMyClass ThingInB("Hello World");
> > return ThingInB;
> > }
>
> Have you tried compiling this?

Nope it's a piece of air code that failed to illustrate something I was
trying to understand.

>
> What do you mean by "function"?

Some of my "native" javascript introduced there. Should be void and
CMyClass.

>
> Apart from that, a() would not compile as there is no constructor for
> CMyClass which takes no arguments.

Ah ok I see.

>
> And you need to understand that copying a pointer is not the same as
copying
> the thing it points to (and/or that the default copy constructor of
CMyClass
> copies a pointer.)

Yep I do comprehend the difference between a pointer and the data it points
to.

What's a "default copy constructor" ?

Thanks,

Anthony.




Re: C++ 101 dumb question by Ulrich

Ulrich
Thu Jun 21 06:46:47 CDT 2007

Anthony Jones wrote:
> I'm new to C++ [...]

Some resources for you:
- comp.lang.c++.moderated and alt.comp.lang.learn.c-c++ on the Usenet.
- http://accu.org - that website has book reviews, don't base your efforts
on anything below the 'recommended' rating, preferable even 'highly
recommended'.
- http://parashift.com hosts the C++ FAQ

> Class CMyClass
> {
> CMyClass(char * str)
[...]
> ~CMyClass(void)

In C++, an empty list of arguments means the same as 'void' here, so you can
as well leave it.

[...]
> CMyClass ThingInB("Hello World");

Note: the string literal '"Hello World"' is a const (read-only) array of 12
chars. The conversion to a pointer to non-const (read-write) pointer to
char is only for compatibility with C. Don't use this conversion, as
modifying the literal will lead to errors during runtime (...will cause
undefined behaviour).

Otherwise you were already given some good advise, in particular not to
reinvent string handling but use existing string classes.

Uli


Re: C++ 101 dumb question by David

David
Thu Jun 21 08:06:56 CDT 2007

Anthony Jones wrote:

> Yep I do comprehend the difference between a pointer and the data it points
> to.
>
> What's a "default copy constructor" ?

Anthony:

If you have to ask this question, then you certainly have not understood
the issues related to passing by value and passing by reference (or
pointer) in C++.

--
David Wilkinson
Visual C++ MVP

Re: C++ 101 dumb question by David

David
Thu Jun 21 07:18:17 CDT 2007


"Anthony Jones" <Ant@yadayadayada.com> wrote in message
news:ukC%23bl$sHHA.4548@TK2MSFTNGP04.phx.gbl...

>> And you need to understand that copying a pointer is not the same as
> copying
>> the thing it points to (and/or that the default copy constructor of
> CMyClass
>> copies a pointer.)
>
> Yep I do comprehend the difference between a pointer and the data it
> points
> to.

In that case, I suspect you have some other misconception about the fate of
the data pointed to by all your char * pointers and/or what happens when you
include something like ...="Hello world" in the program.

> What's a "default copy constructor" ?

If you have a CMyClass a;

The statements

CMyClass b = a;

or

CMyClass b(a);

invoke a "copy constructor" to construct b. If you don't provide one
explicitly, you are liable to get a default version of it supplied by the
compiler. Its action is to copy the data members of the class, member by
member. If (as in your case) one of those members is a pointer, then
you'll create a copy of the pointer, and not a copy of the data it points
to. When that data goes out of scope, you'll find yourself with a pointer
to junk.

So if a class contains a pointer to data which it *owns*, then the copy
constructor must make a copy of the data and set its pointer to point at the
copy. [There are string classes which come complete with copy constructors
which manage all that. If you use standard nul-terminated strings as in C,
then you have to do it yourself.]

(NB Functions which return a class will also call the copy constructor,
even though neither of the above statements occur explicitly in that form,
as a copy of the class being returned is placed on the stack for the benefit
of the calling function. The same is true if you call a function with a
class as one of its arguments.)

Dave

--
David Webber
Author of 'Mozart the Music Processor'
http://www.mozart.co.uk
For discussion/support see
http://www.mozart.co.uk/mzusers/mailinglist.htm


Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 07:21:39 CDT 2007


"David Wilkinson" <no-reply@effisols.com> wrote in message
news:OFWXby$sHHA.3556@TK2MSFTNGP05.phx.gbl...
> Anthony Jones wrote:
>
> > Yep I do comprehend the difference between a pointer and the data it
points
> > to.
> >
> > What's a "default copy constructor" ?
>
> Anthony:
>
> If you have to ask this question, then you certainly have not understood
> the issues related to passing by value and passing by reference (or
> pointer) in C++.
>

Yes the key phrase there being "in C++". "default copy constructor" sounds
very C++ and it's C++ and how it's syntax maps on mechanisms I am familiar
with that is causing me confusion.

Obviously I'm more ignorant than I thought.

The question remains unanswered; What is a default copy constructor?








Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 07:50:12 CDT 2007


"David Webber" <dave@musical-dot-demon-dot-co.uk> wrote in message
news:%23H5iJ5$sHHA.4796@TK2MSFTNGP04.phx.gbl...
>
> "Anthony Jones" <Ant@yadayadayada.com> wrote in message
> news:ukC%23bl$sHHA.4548@TK2MSFTNGP04.phx.gbl...
>
> >> And you need to understand that copying a pointer is not the same as
> > copying
> >> the thing it points to (and/or that the default copy constructor of
> > CMyClass
> >> copies a pointer.)
> >
> > Yep I do comprehend the difference between a pointer and the data it
> > points
> > to.
>
> In that case, I suspect you have some other misconception about the fate
of
> the data pointed to by all your char * pointers and/or what happens when
you
> include something like ...="Hello world" in the program.
>
> > What's a "default copy constructor" ?
>
> If you have a CMyClass a;
>
> The statements
>
> CMyClass b = a;
>
> or
>
> CMyClass b(a);
>
> invoke a "copy constructor" to construct b. If you don't provide one
> explicitly,

What does the signature of a copy constructor look like?

CMyClass(CMyClass src);

OR

is it:-

CMyClass& operator=(CMyClass& src);

> you are liable to get a default version of it supplied by the
> compiler. Its action is to copy the data members of the class, member by
> member. If (as in your case) one of those members is a pointer, then
> you'll create a copy of the pointer, and not a copy of the data it points
> to. When that data goes out of scope, you'll find yourself with a
pointer
> to junk.

Right I get that. What if the member was an instance of class that does
have it's own copy constructor would the default copy constructor call that
to copy the member or would it blindly copy the members of that object as
well? That to me is the critical question.

>
> So if a class contains a pointer to data which it *owns*, then the copy
> constructor must make a copy of the data and set its pointer to point at
the
> copy. [There are string classes which come complete with copy
constructors
> which manage all that. If you use standard nul-terminated strings as in
C,
> then you have to do it yourself.]

Ok got that.

>
> (NB Functions which return a class will also call the copy constructor,
> even though neither of the above statements occur explicitly in that form,
> as a copy of the class being returned is placed on the stack for the
benefit
> of the calling function. The same is true if you call a function with a
> class as one of its arguments.)

Surely that could be optimised away. The existing object is already on the
stack. Are you saying a second copy gets added to the stack, then the
original has it's destructor called, then after returning execution to the
caller another copy is performed, then presumably this temporary copy in the
stack has it's destructor called?

Perhaps I'm showing my ignorance again but since the callee knows its to
return an object it has on the stack it could defer its destruction to the
caller. The caller could perform the copy constructor once then destroy the
object from the callee function.


>
> Dave
>
> --
> David Webber
> Author of 'Mozart the Music Processor'
> http://www.mozart.co.uk
> For discussion/support see
> http://www.mozart.co.uk/mzusers/mailinglist.htm
>



Re: C++ 101 dumb question by David

David
Thu Jun 21 09:06:58 CDT 2007

Anthony Jones wrote:

> What does the signature of a copy constructor look like?
>
> CMyClass(CMyClass src);
>
> OR
>
> is it:-
>
> CMyClass& operator=(CMyClass& src);

> What if the member was an instance of class that does
> have it's own copy constructor would the default copy constructor call that
> to copy the member or would it blindly copy the members of that object as
> well? That to me is the critical question.
>
> Surely that could be optimised away. The existing object is already on the
> stack. Are you saying a second copy gets added to the stack, then the
> original has it's destructor called, then after returning execution to the
> caller another copy is performed, then presumably this temporary copy in the
> stack has it's destructor called?
>
> Perhaps I'm showing my ignorance again but since the callee knows its to
> return an object it has on the stack it could defer its destruction to the
> caller. The caller could perform the copy constructor once then destroy the
> object from the callee function.

Copy constructor:

CMyClass(const CMyClass& src);

Assignment operator

CMyClass& operator = (const CMyClass& src);

When you copy or assign, the copy constructor and assignment operator
that you have defined are used. If you have not defined one, the default
one is used. The default one does member-wise copy or assignment. This
rule is applied recursively.

There is a thing called Return Value Optimization, which in some cases
can eliminate unnecessary copying. However, your classes must be
designed so that all the unnecessary copying would be done correctly if
it were done.

--
David Wilkinson
Visual C++ MVP

Re: C++ 101 dumb question by Ben

Ben
Thu Jun 21 08:36:03 CDT 2007

> CMyClass(CMyClass src);

Almost... but here you have specified pass-by-value, which requires a copy
of the actual parameter to be made, which requires a call to the copy
constructor...

The real copy constructor is

CMyClass(const CMyClass& src);
or
CMyClass(CMyClass& src);

The second case is used only for move semantics, which are very rare
(std::auto_ptr is the only common class using it).

>
> OR
>
> is it:-
>
> CMyClass& operator=(CMyClass& src);
>
>> you are liable to get a default version of it supplied by the
>> compiler. Its action is to copy the data members of the class, member by
>> member. If (as in your case) one of those members is a pointer, then
>> you'll create a copy of the pointer, and not a copy of the data it points
>> to. When that data goes out of scope, you'll find yourself with a
> pointer
>> to junk.
>
> Right I get that. What if the member was an instance of class that does
> have it's own copy constructor would the default copy constructor call
> that
> to copy the member or would it blindly copy the members of that object as
> well? That to me is the critical question.
>
>>
>> So if a class contains a pointer to data which it *owns*, then the copy
>> constructor must make a copy of the data and set its pointer to point at
> the
>> copy. [There are string classes which come complete with copy
> constructors
>> which manage all that. If you use standard nul-terminated strings as in
> C,
>> then you have to do it yourself.]
>
> Ok got that.
>
>>
>> (NB Functions which return a class will also call the copy constructor,
>> even though neither of the above statements occur explicitly in that
>> form,
>> as a copy of the class being returned is placed on the stack for the
> benefit
>> of the calling function. The same is true if you call a function with a
>> class as one of its arguments.)
>
> Surely that could be optimised away. The existing object is already on
> the
> stack. Are you saying a second copy gets added to the stack, then the
> original has it's destructor called, then after returning execution to the
> caller another copy is performed, then presumably this temporary copy in
> the
> stack has it's destructor called?
>
> Perhaps I'm showing my ignorance again but since the callee knows its to
> return an object it has on the stack it could defer its destruction to the
> caller. The caller could perform the copy constructor once then destroy
> the
> object from the callee function.
>
>
>>
>> Dave
>>
>> --
>> David Webber
>> Author of 'Mozart the Music Processor'
>> http://www.mozart.co.uk
>> For discussion/support see
>> http://www.mozart.co.uk/mzusers/mailinglist.htm
>>
>
>



Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 08:36:51 CDT 2007


"David Wilkinson" <no-reply@effisols.com> wrote in message
news:eXno%23TAtHHA.4612@TK2MSFTNGP04.phx.gbl...
> Anthony Jones wrote:
>
> > What does the signature of a copy constructor look like?
> >
> > CMyClass(CMyClass src);
> >
> > OR
> >
> > is it:-
> >
> > CMyClass& operator=(CMyClass& src);
>
> > What if the member was an instance of class that does
> > have it's own copy constructor would the default copy constructor call
that
> > to copy the member or would it blindly copy the members of that object
as
> > well? That to me is the critical question.
> >
> > Surely that could be optimised away. The existing object is already on
the
> > stack. Are you saying a second copy gets added to the stack, then the
> > original has it's destructor called, then after returning execution to
the
> > caller another copy is performed, then presumably this temporary copy in
the
> > stack has it's destructor called?
> >
> > Perhaps I'm showing my ignorance again but since the callee knows its to
> > return an object it has on the stack it could defer its destruction to
the
> > caller. The caller could perform the copy constructor once then destroy
the
> > object from the callee function.
>
> Copy constructor:
>
> CMyClass(const CMyClass& src);
>
> Assignment operator
>
> CMyClass& operator = (const CMyClass& src);
>
> When you copy or assign, the copy constructor and assignment operator
> that you have defined are used. If you have not defined one, the default
> one is used. The default one does member-wise copy or assignment. This
> rule is applied recursively.
>
> There is a thing called Return Value Optimization, which in some cases
> can eliminate unnecessary copying. However, your classes must be
> designed so that all the unnecessary copying would be done correctly if
> it were done.


Everyone,

Thanks for your help that has cleared a lot up for me.

I've also learnt what it feels like being on the other side of
expert/beginner conversation. I'll try to remember it in my answers in
other NGs ;).



>
> --
> David Wilkinson
> Visual C++ MVP



Re: C++ 101 dumb question by Ben

Ben
Thu Jun 21 08:39:36 CDT 2007


"Anthony Jones" <Ant@yadayadayada.com> wrote in message
news:e2Popb$sHHA.1208@TK2MSFTNGP05.phx.gbl...
>
> "MrAsm" <mrasm@usa.com> wrote in message
> news:5akk7311l2bch65l9s6ig363t9dmsgsp9e@4ax.com...
>> On Thu, 21 Jun 2007 10:29:38 +0100, "Anthony Jones"
>> <Ant@yadayadayada.com> wrote:
>>
>>
>> >Class CMyClass
>> >{
>> >private:
>> > char * m_str;
>> >public:
>> > CMyClass(char * str)
>> > {
>> > m_str = str;
>> > }
>> > ~CMyClass(void)
>> > {
>> > // Do I need to anything with m_str
>> > }
>> >}
>>
>> In addition to what SvenC wrote, I'd like to add that, if you use raw
>> pointers (like tha 'char *'), you also need to implement a copy
>> constructor and operator= in your class, e.g.:
>>
>> // Copy ctor
>> CMyClass( const CMyClass & );
>>
>> // operator=
>> CMyClass & operator=( const CMyClass & );
>>
>> and maybe also define your destructor to be 'virtual', to be safe e.g.
>> with inheritance:
>>
>> virtual ~CMyClass();
>>
>> C++ has several subtle things, that you don't find in C# or
>> Javascript... You'd better taking a good C++ book and study it and
>> *write* lots of code (and debug it, to learn a lot also from your
>> errors).
>>
>> I wish you a great experience learning C++!
>>
>> MrAsm
>
> Thanks guys for your input. I had my suspicion that the answer is
> ultimately 'go read a book' however that (along with using the Web) is
> what
> I am doing. As you've guessed I spend most of my time writing Javascript
> and I will continue to do so. However I'm also required to maintain and
> developer an ISAPI filter which up to now has be fairly basic but is
> getting
> more complex.
>
> I dumbed down the example in a (failed) attempt to focus on a particular
> area which so far in my studies seems somewhat ambigous. I'm hoping that
> some one can say something in such that the penny will drop. Let me bring
> up the detail a little (and ditch the distracting string stuff in real
> code
> I'm using CString).
>
> My main focus is the behaviour of the return of a function. Nothing I've
> read so far explains step by step what actually happens when returning a
> object. Here is better example:-
>
> Crypto.h
> =======
> class Crypto
> {
> public:
> Crypto();
> ~Crypto();
> //Public methods here
> private:
> HCRYPTPROV m_hProv;
> };
>
> Crypto.cpp
> =========
> #include "StdAfx.h"
> #include "Crypto.h"
>
> Crypto::Crypto(void)
> {
> m_hProv = 0;
> CryptAcquireContext(&m_hProv, 0, 0, PROV_RSA_FULL,
> CRYPT_MACHINE_KEYSET | CRYPT_SILENT |
> CRYPT_VERIFYCONTEXT);
> };
> Crypto::~Crypto(void)
> {
> if (m_hProv != 0) CryptReleaseContext(m_hProv, 0);
> };
> // Other method implementations here
>
>
> Now I use this class like this:-
>
> void a()
> {
> Crypto oCryptoInA;
> oCryptoInA = b();
> }
>
> Crypto b()
> {
> Crypto oCryptoInB;
> return oCryptoInB;
> }
>
> Now at guess the sequence of events on return in b is:-
>
> Destructor of Crypto is called where this is oCryptoInA.

Nope. oCryptoInA is still alive until it leaves scope.

>
> Data members at oCryptoInB are copied in to oCryptoInA (this is a simple
> mem
> copy since no operator= is defined).

Yes.

>
> Destructor of Crypto is called where this is oCryptoInB.

No, actually this is called earlier. oCryptoInB is copied into a temporary
return value by the return statement, then oCryptoInB is destroyed.

At this point in your program the temporary return value will be destroyed.

>
> This leaves m_hProv in oCryptoInA holding a handle that has now been
> released.

That's true.

>
> Have I got the sequence right? What represents a good solution?

Define operator= to close the handle previously held in the object, and use
DuplicateHandle to get a copy of the right-hand-side's handle. But be
careful about x = x, when (this == &rhs) you should just do nothing.

>
> If I were to substitute the simple handle of m_hCrypto with a COM Smart
> pointer would I be the same sort of bother. That is without an
> implementation of operator= the smart point will not track the correct
> number of references and destory the object prematurely.



Re: C++ 101 dumb question by Ben

Ben
Thu Jun 21 08:41:55 CDT 2007

> The question remains unanswered; What is a default copy constructor?

The copy constructor is used to copy an object, either by initialization:

MyClass a; // no-arg constructor
MyClass b = a; // copy constructor

or for pass-by-value, where the function gets a copy of the actual
parameter:

void f(MyClass p);

If you do not declare a copy constructor, the compiler defines one for you
which just copies each member independently. That is what is meant by
"default" copy constructor.



Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 09:23:32 CDT 2007


"Ben Voigt [C++ MVP]" <rbv@nospam.nospam> wrote in message
news:%234mbjmAtHHA.1672@TK2MSFTNGP06.phx.gbl...
>
>
> Define operator= to close the handle previously held in the object, and
use
> DuplicateHandle to get a copy of the right-hand-side's handle. But be
> careful about x = x, when (this == &rhs) you should just do nothing.
>

Thanks Ben. Now that I'm beginning to under the copy constructor and
assigment operator a little better. The question of dealing with members
which specifically are handles did cross my mind.

In a copy constructor I merely have to duplicate the handle in the src.

In an assignment I need to release any existing handle and duplicate the one
from the source. A special case arises where src and this are the same
object. In this case do nothing otherwise I'll be attempting to duplicate a
handle I've just released.

The specific case for Cryptographic contexts duplicate handle doesn't apply.
CryptContextAddRef is used instead to increase the number of
CryptoReleaseContexts needed to actually release the context.


Crypto& Crypto::operator = (const Crypto& src)
{
if (this != src)
{
if (m_hProv) CryptReleaseContext(m_hProv, 0);
}

m_hProv = src.m_hProv;

CryptContextAddRef(m_hProv, 0, 0);
}

A couple of issues I'm not sure of:-

Do I need to implement a != operator?
Can I access the m_hProv private member of src with src.m_hProv?




Re: C++ 101 dumb question by Ben

Ben
Thu Jun 21 09:57:48 CDT 2007


"Anthony Jones" <Ant@yadayadayada.com> wrote in message
news:uxddA$AtHHA.1672@TK2MSFTNGP06.phx.gbl...
>
> "Ben Voigt [C++ MVP]" <rbv@nospam.nospam> wrote in message
> news:%234mbjmAtHHA.1672@TK2MSFTNGP06.phx.gbl...
>>
>>
>> Define operator= to close the handle previously held in the object, and
> use
>> DuplicateHandle to get a copy of the right-hand-side's handle. But be
>> careful about x = x, when (this == &rhs) you should just do nothing.
>>
>
> Thanks Ben. Now that I'm beginning to under the copy constructor and
> assigment operator a little better. The question of dealing with members
> which specifically are handles did cross my mind.
>
> In a copy constructor I merely have to duplicate the handle in the src.
>
> In an assignment I need to release any existing handle and duplicate the
> one
> from the source. A special case arises where src and this are the same
> object. In this case do nothing otherwise I'll be attempting to duplicate
> a
> handle I've just released.
>
> The specific case for Cryptographic contexts duplicate handle doesn't
> apply.
> CryptContextAddRef is used instead to increase the number of
> CryptoReleaseContexts needed to actually release the context.
>
>
> Crypto& Crypto::operator = (const Crypto& src)
> {
> if (this != src)
> {
> if (m_hProv) CryptReleaseContext(m_hProv, 0);
> }
>
> m_hProv = src.m_hProv;
>
> CryptContextAddRef(m_hProv, 0, 0);
> }

Getting close.

Crypto& Crypto::operator = (const Crypto& src)
{
if (this != &src)
{
if (m_hProv) CryptReleaseContext(m_hProv, 0);

m_hProv = src.m_hProv;

if (m_hProv) CryptContextAddRef(m_hProv, 0, 0);
}
}

>
> A couple of issues I'm not sure of:-
>
> Do I need to implement a != operator?

Does comparing Crypto objects to each other make sense? Remember != is the
opposite of ==, not of =.

> Can I access the m_hProv private member of src with src.m_hProv?

Yes, any member of Crypto can access private members of any Crypto object,
not just "this".



Re: C++ 101 dumb question by David

David
Thu Jun 21 11:07:20 CDT 2007

Anthony Jones wrote:

> Thanks Ben. Now that I'm beginning to under the copy constructor and
> assigment operator a little better. The question of dealing with members
> which specifically are handles did cross my mind.
>
> In a copy constructor I merely have to duplicate the handle in the src.
>
> In an assignment I need to release any existing handle and duplicate the one
> from the source. A special case arises where src and this are the same
> object. In this case do nothing otherwise I'll be attempting to duplicate a
> handle I've just released.
>
> The specific case for Cryptographic contexts duplicate handle doesn't apply.
> CryptContextAddRef is used instead to increase the number of
> CryptoReleaseContexts needed to actually release the context.
>
>
> Crypto& Crypto::operator = (const Crypto& src)
> {
> if (this != src)
> {
> if (m_hProv) CryptReleaseContext(m_hProv, 0);
> }
>
> m_hProv = src.m_hProv;
>
> CryptContextAddRef(m_hProv, 0, 0);
> }
>
> A couple of issues I'm not sure of:-
>
> Do I need to implement a != operator?
> Can I access the m_hProv private member of src with src.m_hProv?

Anthony:

You do not need to define != (or ==) operator unless you use them. But
you do need to define a copy constructor and destructor. Typically, you
have "The Rule of Three" which says that if you need to write any of

copy constructor
assignment operator
destructor

then you need to write all of them.

--
David Wilkinson
Visual C++ MVP

Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 10:14:08 CDT 2007


"Ben Voigt [C++ MVP]" <rbv@nospam.nospam> wrote in message
news:OZGxPSBtHHA.4916@TK2MSFTNGP04.phx.gbl...
>
> "Anthony Jones" <Ant@yadayadayada.com> wrote in message
> news:uxddA$AtHHA.1672@TK2MSFTNGP06.phx.gbl...
> >
> > "Ben Voigt [C++ MVP]" <rbv@nospam.nospam> wrote in message
> > news:%234mbjmAtHHA.1672@TK2MSFTNGP06.phx.gbl...
> >>
> >>
> >> Define operator= to close the handle previously held in the object, and
> > use
> >> DuplicateHandle to get a copy of the right-hand-side's handle. But be
> >> careful about x = x, when (this == &rhs) you should just do nothing.
> >>
> >
> > Thanks Ben. Now that I'm beginning to under the copy constructor and
> > assigment operator a little better. The question of dealing with
members
> > which specifically are handles did cross my mind.
> >
> > In a copy constructor I merely have to duplicate the handle in the src.
> >
> > In an assignment I need to release any existing handle and duplicate the
> > one
> > from the source. A special case arises where src and this are the same
> > object. In this case do nothing otherwise I'll be attempting to
duplicate
> > a
> > handle I've just released.
> >
> > The specific case for Cryptographic contexts duplicate handle doesn't
> > apply.
> > CryptContextAddRef is used instead to increase the number of
> > CryptoReleaseContexts needed to actually release the context.
> >
> >
> > Crypto& Crypto::operator = (const Crypto& src)
> > {
> > if (this != src)
> > {
> > if (m_hProv) CryptReleaseContext(m_hProv, 0);
> > }
> >
> > m_hProv = src.m_hProv;
> >
> > CryptContextAddRef(m_hProv, 0, 0);
> > }
>
> Getting close.
>
> Crypto& Crypto::operator = (const Crypto& src)
> {
> if (this != &src)
> {
> if (m_hProv) CryptReleaseContext(m_hProv, 0);
>
> m_hProv = src.m_hProv;
>
> if (m_hProv) CryptContextAddRef(m_hProv, 0, 0);
> }
> }

Thanks dumb logic mistake and & on the src

>
> >
> > A couple of issues I'm not sure of:-
> >
> > Do I need to implement a != operator?
>
> Does comparing Crypto objects to each other make sense? Remember != is
the
> opposite of ==, not of =.
>

I guess I asked that since I wasn't sure how this != src (or this != &src)
was working.
This would be testing the identity of the object as in its address in
memory.
Ultimately I don't know what const Crypto& src is actually doing. I've used
& to make calls to something that uses * but I'm not familiar with & in the
function signature. What's that called?

(C++ is frustrating in that in order to understand such a thing you need to
be able to look it up in the documentation and in order to do that you need
to know what text to look for.)


> > Can I access the m_hProv private member of src with src.m_hProv?
>
> Yes, any member of Crypto can access private members of any Crypto object,
> not just "this".
>

Wah hey that was a good guess then ;)

Thanks for your patience.



Re: C++ 101 dumb question by MrAsm

MrAsm
Thu Jun 21 10:31:55 CDT 2007

On Thu, 21 Jun 2007 11:07:20 -0500, David Wilkinson
<no-reply@effisols.com> wrote:

>Typically, you
>have "The Rule of Three" which says that if you need to write any of
>
>copy constructor
>assignment operator
>destructor
>
>then you need to write all of them.

And if he wants to be safe when deriving classes, he might consider
defining the destructor *virtual*.

MrAsm

Re: C++ 101 dumb question by David

David
Thu Jun 21 11:40:30 CDT 2007

Anthony Jones wrote:

> I guess I asked that since I wasn't sure how this != src (or this != &src)
> was working.
> This would be testing the identity of the object as in its address in
> memory.
> Ultimately I don't know what const Crypto& src is actually doing. I've used
> & to make calls to something that uses * but I'm not familiar with & in the
> function signature. What's that called?

Anthony:

It really is not possible to learn C++ by repeated newsgroup questions
of this kind. Even as a beginner, you must clearly understand the
meaning of pointers (*), references (&) and the const keyword before you
can make any progress on the language. You must also understand the
related concepts of pass by value, pass by (const) pointer and pass by
(const) reference.

Writing non-trivial copy constructors and assignment operators is a more
of an intermediate level task. If you do not copy or assign your objects
(or pass them by value) you may not need to define these operations.

--
David Wilkinson
Visual C++ MVP

Re: C++ 101 dumb question by Anthony

Anthony
Thu Jun 21 11:11:36 CDT 2007


"David Wilkinson" <no-reply@effisols.com> wrote in message
news:%23b8nwpBtHHA.4952@TK2MSFTNGP04.phx.gbl...
> Anthony Jones wrote:
>
> > I guess I asked that since I wasn't sure how this != src (or this !=
&src)
> > was working.
> > This would be testing the identity of the object as in its address in
> > memory.
> > Ultimately I don't know what const Crypto& src is actually doing. I've
used
> > & to make calls to something that uses * but I'm not familiar with & in
the
> > function signature. What's that called?
>
> Anthony:
>
> It really is not possible to learn C++ by repeated newsgroup questions
> of this kind. Even as a beginner, you must clearly understand the
> meaning of pointers (*), references (&) and the const keyword before you
> can make any progress on the language. You must also understand the
> related concepts of pass by value, pass by (const) pointer and pass by
> (const) reference.
>
> Writing non-trivial copy constructors and assignment operators is a more
> of an intermediate level task. If you do not copy or assign your objects
> (or pass them by value) you may not need to define these operations.
>

David,

Sorry you have found my approach to learning frustrating.

Have you got any suggestions where I can learn these things properly so that
I can stop bothering you with these stupid questions.

Where for example would I find documentation that described what const
MyClass& src is doing?

Cheers,

Anthony.

> --
> David Wilkinson
> Visual C++ MVP



Re: C++ 101 dumb question by MrAsm

MrAsm
Thu Jun 21 11:30:49 CDT 2007

On Thu, 21 Jun 2007 17:11:36 +0100, "Anthony Jones"
<Ant@yadayadayada.com> wrote:


>Where for example would I find documentation that described what const
>MyClass& src is doing?

IMHO you might consider "Thinking in C++", also freely available for
download:

http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html

There is also the book by C++ father himself: "The C++ Programming
Language":

http://www.research.att.com/~bs/3rd.html

HTH,
MrAsm

Re: C++ 101 dumb question by Igor

Igor
Thu Jun 21 11:34:56 CDT 2007

Anthony Jones <Ant@yadayadayada.com> wrote:
> Have you got any suggestions where I can learn these things properly
> so that I can stop bothering you with these stupid questions.

Two books are most often recommended for beginners (dislaimer: I haven't
actually read either):

"Accelerated C++" by Andrew Koenig and Barbara Moo
http://www.acceleratedcpp.com/
http://www.amazon.com/Accelerated-C-Practical-Programming-Example/dp/020170353X

"Thinking in C++" by Bruce Eckel
http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html
http://www.amazon.com/Thinking-C%2B%2B-Introduction-Standard-2nd/dp/0139798099
http://www.amazon.com/Thinking-Vol-Practical-Programming-Second/dp/0130353132

The second book comes as a free download, if you don't want a printed
copy.
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is