Question

pointers and copy on write

Asked by: kuntilanak

I guess I've asked a question related to this here. I am implementing a polynomial class and trying to implement it as a copy on write. I am particularly confused with the following situation..

After I do a[2] then b and c should also be 120x^2 + 10x + 90 right?

Polynomial a,b,c 
//initially a is 2x^2 + 10x + 90
a.initPolynomial("2x^2 + 10x + 90"); 
b = a;
c = a; 
//change the coefficient of the second power to 120 so it 
//now becomes 120x^2 + 10x + 90
a[2] = 120;

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-02 at 20:11:50ID24866100
Topics

C++ Programming Language

,

C Programming Language

Participating Experts
3
Points
500
Comments
33

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Pointers and classes
    In Delphi, you "reach" a class and its functions by a pointer... TLabel(PointerToALabel).Caption := '1'; So... In a VC++ project I'm working on I've got a list of pointers to several different classes, I wonder what I should write to get the same result I can get...
  2. Polynomial Extrapolation in Excel
    Hi, I am using Excel 97. Inside Excel charts, there is a polynomial trending approximation. What is the equivalent of this in spreadsheet functions? I found that exponential is GROWTH, and linear is LINEST, but I couldn't find polynomial. Any help or hints would be appreci...
  3. Need help with Polynomial class
    I am having problems with my implimenation file. The functions reserve, eval and addition keep are where the bulk of my errors coming up. I can't understand why because i have seen it written the same way by other and they had no problems. // Driver program for the polynomia...
  4. Polynomial in C++
    I have problem with polynomial. A program witten by C++ input : 2+3^2+4^6*10+sin30-cos45+........ output: result of polynomial can send to me the code ? send to vhm1985@yahoo.com thanks

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Infinity08Posted on 2009-11-02 at 23:27:23ID: 25726661

>> After I do a[2] then b and c should also be 120x^2 + 10x + 90 right?

That would mean you haven't performed a copy operation here :

>> b = a;
>> c = a;

But simply made b and c refer to a.

As long as none of the three are modified, they can all share the same memory, but as soon as you modify one of them, you'd have to implement your "copy-on-write" logic.

 

by: Let_Me_BePosted on 2009-11-03 at 01:07:48ID: 25727124

The copy on write has to be triggered when you access a non-const member of an instance that is currently a shallow copy.

In the context of your example b and c should be marked as shallow copies. Then when modifying the coeficient, the copy on write should be triggered.

 

by: Infinity08Posted on 2009-11-03 at 02:34:49ID: 25727551

>> In the context of your example b and c should be marked as shallow copies.

It's imo easier to mark all three as shallow copies, that way, a modification to one object doesn't have an impact on other objects.

 

by: Let_Me_BePosted on 2009-11-03 at 03:07:39ID: 25727710

If you create a new instance (not by copy or assignment) then there is no point in marking it as shallow. Actually that would be wrong, because there is no source for the shallow copy.

 

by: Infinity08Posted on 2009-11-03 at 03:21:07ID: 25727781

>> Actually that would be wrong, because there is no source for the shallow copy.

There is if you make one. Using a shared_ptr eg.

 

by: kuntilanakPosted on 2009-11-03 at 06:08:21ID: 25729035

okay, thanks for suggestions

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 06:42:21ID: 25729363

Can you post your code ?

 

by: kuntilanakPosted on 2009-11-03 at 07:13:55ID: 25729693

here's my code so far, if you can comment on it, it would be great

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 07:57:09ID: 25730202

>>>> const void PolyClass::initPolynomial(int index, int c)

What do you want achieve using "const void"?

>>>>   (pol_s->pol)[index] = c;

Before doing that the initPolynomial function should make sure that it has a refcount of 1 or make a copy.

Same applies for clearPoly.

>>>> if (pol_s->refCount > 1){
>>>>    std::map<int, int>::iterator iter;
>>>>    Poly new_map;
>>>>    for (iter = (this->pol_s)->pol.begin(); iter != (this->pol_s)->pol.end(); ++iter)
>>>>       new_map[iter->first] = iter->second;
>>>>    this->pol_s->refCount--;
>>>>    this->pol_s = new PolyStruct();
>>>>    this->pol_s->refCount = 1;
>>>>    this->pol_s->pol = new_map;
>>>>}

put the code above in a member function 'makeSafeCopy' and call it in all non-const member functions and operators before writing to the pol_s member.

>>>>    std::map<int, int>::iterator iter;
>>>>    Poly new_map;
>>>>    for (iter = (this->pol_s)->pol.begin(); iter != (this->pol_s)->pol.end(); ++iter)
>>>>       new_map[iter->first] = iter->second;
>>>>    this->pol_s->refCount--;
>>>>    this->pol_s = new PolyStruct();
>>>>    this->pol_s->refCount = temp;
>>>>    this->pol_s->pol = new_map;

Instead do:

  // decrement the current ref counter
  this->pol_s->refCount--;
  // create a new struct
  PolyStruct * pol_s_new = new PolyStruct();
  // set the counter to 1 (if the constructor didn't do that already)
  pol_s_new->refCount = 1;
  // make a copy of the old map
  pol_s_new->pol          = this->pol_s->pol;
  // Finally take the new pointer for pol_s  (the old pol_s was used in at least one other polynomial)
  this->pol_s = pol_s_new;

 

by: kuntilanakPosted on 2009-11-03 at 08:02:00ID: 25730278

you mean after calling the makeSafeCopy, I need to do the following?

// decrement the current ref counter
  this->pol_s->refCount--;
  // create a new struct
  PolyStruct * pol_s_new = new PolyStruct();
  // set the counter to 1 (if the constructor didn't do that already)
  pol_s_new->refCount = 1;
  // make a copy of the old map
  pol_s_new->pol          = this->pol_s->pol;
  // Finally take the new pointer for pol_s  (the old pol_s was used in at least one other polynomial)
  this->pol_s = pol_s_new;

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: kuntilanakPosted on 2009-11-03 at 08:03:15ID: 25730292

>>Before doing that the initPolynomial function should make sure that it has a refcount of 1 or make a copy.

what if has a refCount > 1? is that what you mean?

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 08:40:26ID: 25730766

>>>> what if has a refCount > 1? is that what you mean?

Yes, but you also can put the if into the makeSafeCopy like

void Polynomial::makeSafeCopy()
{
   if (pol_s->refcount > 1)
   {
       // decrement the current ref counter
       this->pol_s->refCount--;
       // create a new struct
       PolyStruct * pol_s_new = new PolyStruct();
       // set the counter to 1 (if the constructor didn't do that already)
       pol_s_new->refCount = 1;
      // make a copy of the old map
      pol_s_new->pol          = this->pol_s->pol;
      // Finally take the new pointer for pol_s  (the old pol_s was used in at least one other polynomial)
      this->pol_s = pol_s_new;
   }
   // else do nothing
   
}

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 08:41:36ID: 25730780

That would allow you to simply call makeSafeCopy(); in any of the writing functions and operators to assure you have a pol_s member with refcount == 1.

 

by: kuntilanakPosted on 2009-11-03 at 09:03:05ID: 25731028

but even if I don't put that into a makeSafeCopy() method, it would still be fine right?

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 09:36:42ID: 25731400

>>>> but even if I don't put that into a makeSafeCopy() method, it would still be fine right?

Only if you have

    if (this->pol_s->refCount > 1)  
        makeSafeCopy()

in each of those functions (where the if statement seems some unnecessary overhead for me).

 

by: kuntilanakPosted on 2009-11-03 at 09:46:44ID: 25731500

so I do two comparsion in the code above, first is:

this->pol_s->refCount > 1 and next I do if pol_s->refcount > 1

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 09:55:50ID: 25731599

this->pol_s->refCount > 1 is identical to pol_s->refcount > 1

The "this->" is redundant code though it may increase the readability.

If you put the if statement (with or without this->) into the makeSafeCopy you need not repeat it in each member function or operator.

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 09:57:23ID: 25731617

>>>> this->pol_s->refCount > 1 is identical to pol_s->refcount > 1

Of course only if using "refCount"  with a capital C for both.

 

by: kuntilanakPosted on 2009-11-03 at 11:23:45ID: 25732482

I don't see how that will make a difference in the code, as what you're doing is just moving the whole block of code into a method called makesafecopy and then call that everytime we need to do a shallow copy... I know this is better design and yes I do admit it.. but can you please the purpose other than that?

 

by: kuntilanakPosted on 2009-11-03 at 11:34:23ID: 25732597

Here's my updated one, see if it suffices what you suggested me and I am getting what you explained correctly

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 12:03:14ID: 25732940

>>>> I know this is better design and yes I do admit it.. but can you please the purpose other than that?
A better design should be enough reason ;-)

But any redundant code is error-prone and is contrary to object-oriented principles. Assume you want to make the reference counting thread-safe. Then, decrementing and incrementing the reference counter must be made an exclusive operation. Do you want to add this additional code to hundreds of statements in your implementation or only to a few statements?

Look at your implementation posted last. You added the code for checking the reference counter only in a few functions. The majority of operators and functions also changing the member data didn't have the needed code. You may ask yourself why you didn't add the code. Because you didn't know of that the code was needed there as well? Rarely. It is much more likely that you didn't want to copy the same codelines into ten or more functions as you thought that there might be a more elegant solution. You were right.

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 12:18:00ID: 25733089

>>>> Look at your implementation posted last.
I meant the implementation before the last one.

>>>>   if (this->pol_s->refCount > 1){
>>>>      makeSafeCopy();
>>>> }

No. You have the if condition in the makeSafeCopy. So you can omit it when calling makeSafeCopy. Simply do

  makeSafeCopy();

whereever you want to update the polynom.

>>>> PolyClass PolyClass::operator-(){
>>>>  PolyClass result;
>>>>  std::map<int, int>::iterator iter;
>>>>  for (iter = (this->pol_s)->pol.begin(); iter != (this->pol_s)->pol.end(); ++iter)
>>>>       result.initPolynomial(iter->first, -(iter->second));      
>>>>  return result;
>>>> }      

Instead of

     result.initPolynomial(iter->first, -(iter->second));      

you better do

     iter->second = -iter->second;

and call makeSafeCopy() before the iteration.

The point is if you are already on the low level of iterating the internal map, it makes less sense to calling a *higher-level* member function like initPolynomial.

 

by: kuntilanakPosted on 2009-11-03 at 12:59:04ID: 25733545

other than that it's all good?

 

by: kuntilanakPosted on 2009-11-03 at 13:09:40ID: 25733680

and by the way changing it to:

make the unary operation not to work

iter->second = -iter->second;

                                              
1:

Select allOpen in new window

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 13:43:08ID: 25734125

>>>> make the unary operation not to work
Really? Hmmm. The iter-> would/should operate on a reference to the pair stored in the map.

Alternatively try

   std::pair<int, int> & current = *iter;
   current.second = -current.second;

but actually it shouldn't make a difference.

As last resort do

   this->pol_s[iter->first] = -iter->second;

>>>> other than that it's all good?  

Don't know. I didn't have time to make a full check. But you should make some own unit tests so that *all* functions and operators were tested.


 

by: kuntilanakPosted on 2009-11-03 at 13:44:28ID: 25734141

okay, will do... if you have time, do you mind looking at my code again

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 14:06:29ID: 25734325

>>>> bool operator<(const PolyClass& p1, const PolyClass& p2){
>>>>  bool result = false;
>>>>  std::map<int, int>::reverse_iterator i = (p1.pol_s)->pol.rbegin();
>>>>  std::map<int, int>::reverse_iterator j = (p2.pol_s)->pol.rbegin();
>>>>  if (i->first < j->first)
>>>>       result = true;
>>>>  else
>>>>       result = false;
>>>> 
>>>>  return result;
>>>> }


The operators <, <= , >, >=  are wrong. You neither consider empty PolyClass objects nor polynomials where the 'first' coefficient is equal but higher coefficients are different.

bool operator<(const PolyClass& p1, const PolyClass& p2)
{
  // first check for different sizes
  // a *shorter* polynomial should be called the *smaller* one
  if (p1.size() != p2.size())
     return (p1.size() < p2.size());

 std::map<int, int>::reverse_iterator i = (p1.pol_s)->pol.rbegin();
 std::map<int, int>::reverse_iterator j = (p2.pol_s)->pol.rbegin();

 // as the sizes were equal we only need to check for i
 for (; i != p1.pol_s->pol.end(); ++i, ++j)
 {
     if (i->second!= j->second)
         return (i->second < j->second);
 }
 return false;  // all coefficients have been equal
}

Note, with operator== and operator< you can implement all the other comparision operators.

One more note: a for loop is better than a while loop as the incrementation is part of the for statement and it is much more difficult to have an infinite loop.

 

by: kuntilanakPosted on 2009-11-03 at 14:44:21ID: 25734686

thanks for pointing that out, that seems to make more sense

 

by: itsmeandnobodyelsePosted on 2009-11-03 at 23:06:53ID: 25737061

>>>> // first check for different sizes
I reflected about that part and came to a different result. First, the size probably is not a function of PolyClass but of the map in the PolyStruct. Second, if the polynomials have different dimensions then the coefficient of the highest power compared to 0 would determine the comparision between the polynomials. So, we would have the following code:

bool operator<(const PolyClass& p1, const PolyClass& p2)
{
 std::map<int, int>::reverse_iterator i = (p1.pol_s)->pol.rbegin();
 std::map<int, int>::reverse_iterator j = (p2.pol_s)->pol.rbegin();
 
 // we need to check for i and j as any of them could end
 // a new cycle only will happen if the dimensions were equal
 for (;i != p1.pol_s->pol.end() || j != p2.pol_s->pol.end(); ++i, ++j) 
 {
     int d1 = -1;
     int d2 = -1;
     if (i != p1.pol_s->pol.end())
         d1 = i->first;
     if (j != p2.pol_s->pol.end())
         d2 = j->first;
     if (d1 < d2)
     {  // p2 is greater if the coefficient of the higher power >= 0
        return (j->second >= 0); 
     }
     else if (d2 > d1)
     {  // p1 is less if the coefficient of the higher power >= 0
        return (i->second >= 0); 
     }
     // now we have equal dimension and comapre the coefficients
     if (i->second!= j->second)
         return (i->second < j->second);
 }
 return false;  // all coefficients have been equal
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

Select allOpen in new window

 

by: Infinity08Posted on 2009-11-04 at 07:51:52ID: 25740542

Silly me. I thought the question was :

>> After I do a[2] then b and c should also be 120x^2 + 10x + 90 right?

lol

 

by: itsmeandnobodyelsePosted on 2009-11-05 at 09:58:17ID: 25752069

Silly you  ;-)

The question was 'pointers and copy on write' and actually the

   a[2] = 120;

should NOT lead to b and c  is  "120x^2 + 10x + 90"  but they keep on "2x^2 + 10x + 90" what was their initial value.

 

by: Infinity08Posted on 2009-11-05 at 11:11:29ID: 25752799

Come on Alex, no word games ... The only question was the one that ended with a question mark. Everything else after that question was answered was follow-up discussion. What you quote is the question title, and maybe you're psychic, but I can't spot a question in there - just a description of the topic.


>> should NOT lead to b and c  is  "120x^2 + 10x + 90"  but they keep on "2x^2 + 10x + 90" what was their initial value.

Which is what I said :

>> as soon as you modify one of them, you'd have to implement your "copy-on-write" logic.

"one of them" includes 'a', so modifying 'a' implies that a "copy-on-write" has to happen.

 

by: itsmeandnobodyelsePosted on 2009-11-06 at 00:10:17ID: 25757448

>>>> Come on Alex, no word games ...
It was one of my last ones before I leave. So you may try to stand it ...

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...