PAGE2GO2 HOME | INTERNET NEWS

LeighExchange - Free Advertising Network Stock Research at Internet Speed Need Money Easy and Quick?

Re: again the problem: the destructor is called twice

 List
Subject: Re: again the problem: the destructor is called twice
Poster: mlimber
Date: 23 Mar 2007 12:45:09 -0700
Related Postings: 1 2 3 4 5 6 7 8 9
On Mar 23, 3:26 pm, "David" wrote:
> On Mar 23, 3:10 pm, "mlimber" wrote:
> > Of course, the "Big Three" (or probably better, the "Big Two" --http://www.artima.com/cppsource/bigtwo.html) problems
> > fixed in any case.
>
> Thanks all for your help. I think I need a "deep copy" in my
> copyconstructor. sorry I am new in C++, so when I tried to do below,
> there was something wrong with this:
> test::test(const test& mytest)
> {
>
> map::iterator ii;

You need

map::const_iterator ii;

since mytest is const.


>
> for(ii=mytest.tests.begin();ii!=mytest.tests.end();++ii)
> {
> myclass* my=new myclass;
> memcpy(my,ii->second,sizeof(ii->second));
> tests.insert(make_pair(ii->first,my));
> }
>
> }
>
> there was an error: "c:\Ug\Solution1\test\test.cpp(16): error C2679:
> binary '=' : no operator found which takes a right-hand operand of
> type 'std::_Tree<_Traits>::const_iterator' " at the for loop point.
> can anybody tell me why and what's the right way to do the copy
> constructor? thanks

Read the article on the law of the Big Two that I gave in my previous post.

Here's a tip: If you see memcpy in C++ code, that's bad (usually). Prefer to give myclass proper copy semantics so you can say:

*my = *( ii->second );

Better still would be to use a smart pointer that does -- depending on your needs -- either reference counting (e.g., std::tr1::shared_ptr, boost::shared_ptr, Loki::SmartPtr, or the one in FAQ 16.22 and following) or deep copying (e.g., Loki::SmartPtr) for you automatically.

Cheers! --M

 

Page2Go2.com is not responsible for content of this message.