Advertisement

04.25.2008 at 08:06PM PDT, ID: 23355400
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

new/delete operator, creating a class in the location as deleted class

Tags: C++
COne* p  = new COne;
delete p;
 CTwo *pp = new CTwo;

p and pp point to different locations generally.
I want pp to be same as p.

CTwo is smaller in size than COne class.
Start your free trial to view this solution
Question Stats
Zone: Programming
Question Asked By: has
Solution Provided By: josgood
Participating Experts: 2
Solution Grade: A
Views: 0
Translate:
Loading Advertisement...
04.25.2008 at 09:08PM PDT, ID: 21444454

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.25.2008 at 09:40PM PDT, ID: 21444534

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.25.2008 at 10:57PM PDT, ID: 21444678

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 01:22AM PDT, ID: 21444891

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 06:06AM PDT, ID: 21445406

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 06:26AM PDT, ID: 21445449

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 12:11PM PDT, ID: 21446556

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 09:37PM PDT, ID: 21448155

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 09:39PM PDT, ID: 21448162

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 09:48PM PDT, ID: 21448183

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.26.2008 at 11:22PM PDT, ID: 21448335

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 01:46AM PDT, ID: 21448537

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 09:50AM PDT, ID: 21449631

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 09:52AM PDT, ID: 21449639

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 09:57AM PDT, ID: 21449647

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 09:59AM PDT, ID: 21449652

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 10:01AM PDT, ID: 21449655

Rank: Master

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 10:52AM PDT, ID: 21449785

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 12:04PM PDT, ID: 21450039

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 06:26PM PDT, ID: 21451035

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 08:26PM PDT, ID: 21451427

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.27.2008 at 10:54PM PDT, ID: 21451767

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.28.2008 at 08:38AM PDT, ID: 21454998

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.28.2008 at 09:03AM PDT, ID: 21455227

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.28.2008 at 10:20AM PDT, ID: 21455772

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
04.28.2008 at 10:36AM PDT, ID: 21455905

Rank: Sage

All comments and solutions are available to Premium Service Members only.

Start your 7-day free trial and see for yourself why Experts Exchange is the easiest and most proven technology resource in the world. Get Started

Already a member? Login to view this solution.

 
 
Loading Advertisement...
Microsoft
  • Internet Protocols
  • Applications
  • Development
  • OS
  • Hardware
  • Windows Security
Apple
  • Operating Systems
  • Hardware
  • Programming
  • Networking
  • Software
Internet
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Spy / Ad Blockers
  • Web Browsers
  • New Net Users
  • Web Development
  • Chat / IM
  • Anti Spam
  • Web Servers
  • Anti-Virus
  • Email Clients
Gamers
  • Tips
  • Online / MMORPG
  • Puzzle
  • Emulators
  • Action / Adventure
  • Role Playing
  • Consoles
  • Game Programming
  • Strategy
  • Sports
  • Misc
  • Computer Games
Digital Living
  • Hardware
  • Automotive
  • New Net Users
  • New Users
  • Software
  • Digital Music
  • Gaming World
  • Home Security
  • Apple
  • Networking Hardware
Virus & Spyware
  • Vulnerabilities
  • IDS
  • Encryption
  • Anti-Virus
  • Operating Systems Security
  • Software Firewalls
  • WebApplications
  • Cell Phones
  • Operating Systems
  • Internet
  • Hardware Firewalls
Hardware
  • Displays / Monitors
  • Handhelds / PDAs
  • Components
  • Peripherals
  • Laptops/Notebooks
  • Servers
  • Misc
  • Apple
  • Embedded Hardware
  • Networking Hardware
  • Storage
  • Desktops
  • New Users
Software
  • System Utilities
  • Industry Specific
  • Network Management
  • Photos / Graphics
  • Page Layout
  • VMware
  • Misc
  • Web Development
  • OS
  • CYGWIN
  • Voice Recognition
  • Virtualization
  • Message Queue
  • Quality Assurance
  • Security
  • Firewalls
  • MultiMedia Applications
  • Development
  • Database
  • Office / Productivity
  • Business Management
  • OS/2 Apps
  • Server Software
  • Internet / Email
ITPro
  • OS
  • Storage
  • Encryption
  • Operating Systems Security
  • Apple Hardware
  • Laptops & Notebooks
  • Servers
  • Networking Hardware
  • Peripherals
  • Devices
  • Displays / Monitors
  • WebTrends / Stats
  • Search Engines
  • Firewalls
  • Web Computing
  • WebApplications
  • IDS
  • Vulnerabilities
  • Email Clients
  • File Sharing
  • Spy / Ad Blockers
  • Web Browsers
  • Web Servers
  • Networking
  • Anti-Virus
  • Consulting
  • Chat / IM
  • Anti Spam
Developer
  • Web Servers
  • Web Browsers
  • Game Programming
  • Dev Tools
  • Industry Specific
  • Office / Productivity
  • Database
  • CYGWIN
  • Web Development
  • Search Engines
  • File Sharing
  • WebTrends / Stats
  • Programming
  • Content Management
  • Application Servers
  • Protocols
Storage
  • Removable Backup Media
  • Storage Technology
  • Servers
  • Grid
  • Remote Access
  • Backup / Restore
  • Misc
  • Hard Drives
OS
  • Miscellaneous
  • Security
  • Development
  • Linux
  • VMware
  • MainFrame OS
  • Unix
  • Apple
  • OS / 2
  • AS / 400
  • BeOS
  • Microsoft
  • VMS / OpenVMS
Database
  • Oracle
  • Miscellaneous
  • MySQL
  • Software
  • Sybase
  • Contact Management
  • PostgreSQL
  • Data Manipulation
  • Clarion
  • InterSystems Cache
  • Siebel
  • MUMPS
  • OLAP
  • SQLBase
  • SAS
  • GIS & GPS
  • 4GL
  • Berkeley DB
  • DB2
  • Informix
  • Interbase / Firebird
  • FoxPro
  • Reporting
  • LDAP
  • Filemaker Pro
  • MS SQL Server
  • dBase
  • MS Access
Security
  • Misc
  • Web Browsers
  • Software Firewalls
  • Operating Systems Security
  • File Sharing
  • Spy / Ad Blockers
  • Vulnerabilities
  • WebApplications
  • IDS
  • Anti-Virus
  • Encryption
  • Anti Spam
  • Email Clients
  • VPN
  • Chat / IM
Programming
  • Editors IDEs
  • Installation
  • Handhelds / PDAs
  • Multimedia Programming
  • System / Kernel
  • Automation
  • Algorithms
  • Game
  • Signal Processing
  • Project Management
  • Open Source
  • Database
  • Misc
  • Languages
  • Processor Platforms
  • Theory
Web Development
  • Scripting
  • Blogs
  • Web Servers
  • Software
  • Search Engines
  • Web Graphics
  • Web Services
  • Images
  • Internet Marketing
  • Images and Photos
  • Components
  • Document Imaging
  • Web Languages/Standards
  • Illustration
  • WebApplications
  • Fonts
  • WebTrends / Stats
  • Authoring
  • Digital Camera Software
  • Miscellaneous
Networking
  • Protocols
  • Apple Networking
  • Network Management
  • Message Queue
  • Application Servers
  • Content Management
  • File Servers
  • Email Servers
  • Misc
  • Java Editors & IDEs
  • Wireless
  • Networking Hardware
  • Backup / Restore
  • System Utilities
  • ISPs & Hosting
  • Web Servers
  • Storage Technology
  • Removable Backup Media
  • Servers
  • Web Computing
  • Broadband
  • Grid
  • OS / 2
  • Novell Netware
  • Unix Networking
  • Windows Networking
  • Security
  • Telecommunications
  • Operating Systems
  • Linux Networking
Other
  • Lounge
  • Business Travel
  • Community Support
  • New Net Users
  • Philosophy / Religion
  • Math / Science
  • Miscellaneous
  • URLs
  • Expert Lounge
  • Politics
  • Puzzles / Riddles
  • Automotive
Community Support
  • Suggestions
  • New to EE
  • New Topics
  • CleanUp
  • Announcements
  • General
  • Feedback
  • Input
  • EE Bugs
 
04.25.2008 at 09:08PM PDT, ID: 21444454

Rank: Master

You want "placement new".  One link is http://www.glenmccl.com/tip_025.htm.  A quick google will give you more.

I see if I can work up an example.
 
04.25.2008 at 09:40PM PDT, ID: 21444534

Rank: Master

Here's the example I promised

#include <cstddef> // for std::size_t
#include <memory>
#include <iostream>

 class COne {
   public:
      // placement new takes an additional parameter, a void* in this case
      static void* operator new(std::size_t size, void* location){ return ::operator new(size,location); }
      // need a corresponding placement delete (only called when an exception is thrown)
      static void operator delete(void *pMemory, void *ptr) { ::operator delete(pMemory,ptr); }
      // global operator new hidden by placement new, so must define one here
      static void* operator new(std::size_t size) { return ::operator new(size); }
      // ditto for the global operator delete, hidden by the placement delete
      static void operator delete(void *pMemory) { ::operator delete(pMemory); }
      //
   private:
      char a;
 };
 
 class CTwo {
   public:
      // placement new and delete
      static void* operator new(std::size_t size, void* location){ return ::operator new(size,location); }
      static void operator delete(void *pMemory, void *ptr) { ::operator delete(pMemory,ptr); }
      // Standard new and delete
      static void* operator new(std::size_t size) { return ::operator new(size); }
      static void operator delete(void *pMemory) { ::operator delete(pMemory); }
   private:
      double b;
 };
 


void main() {
   int sizeRequired = sizeof(CTwo); // since it is larger
   unsigned char* allocation(new unsigned char[sizeRequired]);
   COne* p  = new (allocation) COne;
   std::cout << "COne allocated at location " << std::hex << p << std::endl;
   // >>No<< delete p; Don't delete here because that deletes the new unsigned char[sizeRequired] allocation
    CTwo *pp = new (allocation) CTwo;
   std::cout << "CTwo allocated at location " << std::hex << pp << std::endl;
   delete pp;
}
Accepted Solution
 
04.25.2008 at 10:57PM PDT, ID: 21444678
// NEWDELETE.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

class A
{
      virtual long Increase() = 0;
      virtual long Decrease() = 0;
};

class B : public A
{
      virtual void Set(long n) = 0;
      virtual long Get() = 0;
};

class C : public A
{
public:
      C()
      {
      }
      virtual ~C()
      {
      }
      long Increase(){return -1;}
      long Decrease()
      {
            return -1;
      }
};

class D : public B
{
public:
      D() : m_count(0), m_n(99)
      {
      }
      virtual ~D()
      {
            //
            //new C class has to be created in place of this destructing class
            //so that static_cast<A*>(this) in both has to be same value
            // so that the line "n = pD->Decrease();} below has to return -1
            // instead of crashing.

            // I KNOW FOLLOWING WONT WORK BUT IF IT DID THAT IS WHAT WOULD BE MY SOLUTION!
            C* pC = new C;
            void* pThis = this;
            memcpy(pThis, pC, sizeof(C));
            delete pC;
      }
      long Increase(){return ++m_count;}
      long Decrease()
      {
            if (--m_count == 0)
                  delete this;
            return m_count;
      }
      void Set(long n)
      {
            m_n = n;
      }
      long Get()
      {
            return m_n;
      }
protected:
      long m_count;
      long m_n;
};

int _tmain(int argc, _TCHAR* argv[])
{

      D* pD = new D;
      long n = pD->Increase(); // 1 expected
      n = pD->Get(); // 99 expected
      pD->Set(7);
      n = pD->Get(); // 7 expected
      n = pD->Decrease(); // 0 expected
      n = pD->Decrease(); // crashes but can we allocate new class C in the destructor of C, to this location so this would work fine!!!
//  n must be -1, and not crash!
      return 0;
}

 
04.26.2008 at 01:22AM PDT, ID: 21444891

Rank: Sage

Sorry, in a rush so I didn't get a chance to look at your code in depth, so some cursory observations...

>> long Decrease()
>>       {
>>             if (--m_count == 0)
>>                   delete this;
>>             return m_count;
>>       }

m_count will no longer be valid after the delete, you will be referencing unallocated memory.

>>// I KNOW FOLLOWING WONT WORK BUT IF IT DID THAT IS WHAT WOULD BE MY SOLUTION!
>>            C* pC = new C;
>>            void* pThis = this;
>>            memcpy(pThis, pC, sizeof(C));
>>            delete pC;

Why doesn't placement new work for you?

NB. If you use placement new you MUST explicitly call the destructor on your class yourself, failure to do so will leave any resources allocated by your class or any member objects undestructed, which will result in leaks.

 
04.26.2008 at 06:06AM PDT, ID: 21445406

Rank: Master

Evilrx is right, when using placement new, the destructor must be called explicitly, such as
   p->~COne();

So the main in my example looks like this
void main() {
   int sizeRequired = sizeof(CTwo); // since it is larger
   unsigned char* allocation(new unsigned char[sizeRequired]);
   COne* p  = new (allocation) COne;
   std::cout << "COne allocated at location " << std::hex << p << std::endl;
   // >>No<< delete p; Don't delete here because that deletes the new unsigned char[sizeRequired] allocation
   p->~COne(); // Must call destructor explicitly to free allocated resources
    CTwo *pp = new (allocation) CTwo;
   std::cout << "CTwo allocated at location " << std::hex << pp << std::endl;
   pp->~CTwo();
   delete pp;
}

Thanks for catching that, Rx!

If you can get a copy of "Effective C++ Third Edition" by Scott Meyers, read item 52 "Write placement delete if you write placement new".  Scott spends 6 pages on the subject.  Its the best discussion of this that I have read.
 
04.26.2008 at 06:26AM PDT, ID: 21445449

Rank: Master

>>      n = pD->Decrease(); // 0 expected
This causes Decrease() to call
   delete this;
so that the next call
>>      n = pD->Decrease(); // crashes but can we allocate new class C in the destructor of C, to this location so this would work fine!!!
has no instance and thus crashes, as you say.

Could you tell us the intention of your project?  What would you like to accomplish?

 
04.26.2008 at 12:11PM PDT, ID: 21446556

Rank: Sage

>> Thanks for catching that, Rx!
No worries josgood.

>> If you can get a copy of "Effective C++ Third Edition" by Scott Meyers
http://www.ishiboo.com/~nirva/c++/eff/

-Rx.
 
04.26.2008 at 09:37PM PDT, ID: 21448155
My initial try was placement new, but was not working. If you can make this work fine.
I want to replace it in the destruction.

#include "stdafx.h"
#include <assert.h>
#include <new>

class A
{
      virtual long Increase() = 0;
      virtual long Decrease() = 0;
};

class B : public A
{
      virtual void Set(long n) = 0;
      virtual long Get() = 0;
};

class C : public A
{
public:
      C()
      {
      }
      virtual ~C()
      {
      }
      long Increase(){return -1;}
      long Decrease()
      {
            delete this;
                  return -1;
      }
};

class CReplacer
{
public:
      CReplacer(void* p) : m_p(p)
      {
      }
      virtual ~CReplacer()
      {
            C* pC = new(m_p) C;
            assert(m_p == pC);
      }
private:
      void* m_p;
};

class D : public B
{
public:
      D() : m_count(0), m_n(99)
      {
      }
      virtual ~D()
      {
          CReplacer r(reinterpret_cast<void*>(this));
      }
      long Increase(){return ++m_count;}
      long Decrease()
      {
            if (--m_count == 0)
                  delete this;
            return m_count;
      }
      void Set(long n)
      {
            m_n = n;
      }
      long Get()
      {
            return m_n;
      }
protected:
      long m_count;
      long m_n;
};


int main(int argc, char* argv[])
{
    D* pD = new D;
    long n = pD->Increase();
    n = pD->Get();
    pD->Set(7);
    n = pD->Get();
      n = pD->Decrease();
    n = pD->Decrease();
    return 0;
}

////////////////////////////////////

THIS is not exactly what i want, but this also crashes at  the end.
This one atleast goes to last line. Again my aim is to work the first one above

#include "stdafx.h"
#include <assert.h>
#include <new>

class A
{
      virtual long Increase() = 0;
      virtual long Decrease() = 0;
};

class B : public A
{
      virtual void Set(long n) = 0;
      virtual long Get() = 0;
};

class C : public A
{
public:
      C()
      {
      }
      virtual ~C()
      {
      }
      long Increase(){return -1;}
      long Decrease()
      {
            delete this;
                  return -1;
      }
};

class CReplacer
{
public:
      CReplacer(void* p) : m_p(p)
      {
      }
      virtual ~CReplacer()
      {
            C* pC = new(m_p) C;
            assert(m_p == pC);
      }
private:
      void* m_p;
};

class D : public B
{
public:
      D() : m_count(0), m_n(99)
      {
      }
      virtual ~D()
      {

      }
      long Increase(){return ++m_count;}
      long Decrease()
      {
            if (--m_count == 0)
                  delete this;
            return m_count;
      }
      void Set(long n)
      {
            m_n = n;
      }
      long Get()
      {
            return m_n;
      }
protected:
      long m_count;
      long m_n;
};


int main(int argc, char* argv[])
{
    D* pD = new D;
    long n = pD->Increase();
    n = pD->Get();
    pD->Set(7);
    n = pD->Get();
      {
            CReplacer r(reinterpret_cast<void*>(pD));
            n = pD->Decrease();
      }
    n = pD->Decrease();
    return 0;
}


 
04.26.2008 at 09:39PM PDT, ID: 21448162
Again, I am not against placement new, I just could not have a success yet.
 
04.26.2008 at 09:48PM PDT, ID: 21448183
After looking at my problem again, if the following code runs without crash, it will do it for me.
Thanks.

#include "stdafx.h"
#include <assert.h>
#include <new>

class A
{
      virtual long Increase() = 0;
      virtual long Decrease() = 0;
};

class B : public A
{
      virtual void Set(long n) = 0;
      virtual long Get() = 0;
};

class C : public A
{
public:
      C()
      {
      }
      virtual ~C()
      {
      }
      long Increase(){return -1;}
      long Decrease()
      {
            delete this;
                  return -1;
      }
};

class CReplacer
{
public:
      CReplacer(void* p) : m_p(p)
      {
      }
      virtual ~CReplacer()
      {
            C* pC = new(m_p) C;
            assert(m_p == pC);
      }
private:
      void* m_p;
};

class D : public B
{
public:
      D() : m_count(0), m_n(99)
      {
      }
      virtual ~D()
      {
         
      }
      long Increase(){return ++m_count;}
      long Decrease()
      {
            if (--m_count == 0)
                  delete this;
                 CReplacer r(reinterpret_cast<void*>(this));
            return m_count;
      }
      void Set(long n)
      {
            m_n = n;
      }
      long Get()
      {
            return m_n;
      }
protected:
      long m_count;
      long m_n;
};


int main(int argc, char* argv[])
{
    D* pD = new D;
    long n = pD->Increase();
    n = pD->Get();
    pD->Set(7);
    n = pD->Get();
    n = pD->Decrease();
    n = pD->Decrease();
    return 0;
}
 
04.26.2008 at 11:22PM PDT, ID: 21448335
is this all correct? coding? memory leak etc.
please make suggestions, corrections.
Thanks.

#include "stdafx.h"
#include "stdlib.h"
#include <assert.h>
#include <new>

class A
{
      virtual long Increase() = 0;
      virtual long Decrease() = 0;
};

class B : public A
{
      virtual void Set(long n) = 0;
      virtual long Get() = 0;
};

class C : public A
{
public:
      C() : m_count(1)
      {
      }
      virtual ~C()
      {
      }
      long Increase(){return ++m_count;}
      long Decrease()
      {
              long n = --m_count;
              if (n == 0) {
                  delete this;  // this->~C(); free(this); is better? same ?
              }
          return n;
      }
protected:
      long m_count;
};

class D : public B
{
public:
      D() : m_count(0), m_n(99)
      {
      }
      virtual ~D()
      {
         
      }
      long Increase(){return ++m_count;}
      long Decrease()
      {
              long n = --m_count;
              if (n == 0) {
              this->~D();
                    void* p = realloc(reinterpret_cast<void*>(this), sizeof(C));
                    new(p) C;
              }
           return n;
      }
      void Set(long n)
      {
            m_n = n;
      }
      long Get()
      {
            return m_n;
      }
protected:
      long m_count;
      long m_n;
};


int main(int argc, char* argv[])
{
    D* pD = new D;
    long n = pD->Increase();
    n = pD->Get();
    pD->Set(7);
    n = pD->Get();
      n = pD->Decrease();
    n = pD->Decrease();
    return 0;
}

 
04.27.2008 at 01:46AM PDT, ID: 21448537

Rank: Sage

Wow, lots of code. :)

Ok, if josgood hasn't already done so by the time I return (I'm sure he will have) I will try and look at this in detail later but unfortunately this weekend I am really busy with house maintenance (decorating) so it may not be until tomorrow morning. I would ask you , meanwhile, to clarify exactly what you are trying to do and why. What's the rational for this?
 
04.27.2008 at 09:50AM PDT, ID: 21449631

Rank: Sage

Ok, I've had the chance to have a little look and I've added two comments to your code (see below, my comments begin with RX). I can't provide you with a prefered method for what you are trying to do since you have yet to clarify what the rational is behind this so I don't really know what to advise. All I can say is that trying to mix new/realloc is dangerous. Also, placement new is pretty specialized and its usage comes with many caveats and unless you really need to be using it I think you'd be best to steer clear. Meanwhile, try reading up on hopw to manage memory pools with C++ as this may help you.

http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.14

-Rx.
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:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
#include "stdafx.h"
#include "stdlib.h"
#include <assert.h>
#include <new>
 
class A
{
	virtual long Increase() = 0;
	virtual long Decrease() = 0;
};
 
class B : public A
{
	virtual void Set(long n) = 0;
	virtual long Get() = 0;
};
 
class C : public A
{
public:
	C() : m_count(1)
	{
	}
	virtual ~C()
	{
	}
	long Increase(){return ++m_count;}
	long Decrease()
	{
		long n = --m_count;
		if (n == 0) {
			// RX: This is dangerous, say this is a stack based object? 
			// You should protect agains thtis by making constructor private
			// and using a static factory function
			delete this;
		}
		return n;
	}
protected:
	long m_count;
};
 
class D : public B
{
public:
	D() : m_count(0), m_n(99) 
	{
	}
	virtual ~D()
	{
 
	}
	long Increase(){return ++m_count;}
	long Decrease()
	{
		long n = --m_count;
		if (n == 0) {
			this->~D();
			// RX: It is not safe to mix realloc and new. The original object was allocated using new
			// There is no reason to believe that realloc will work with the same heap as new.
			// Also, say this is a stack based object? You should protect agains thtis by making
			// constructor private and using a static factory function. I'm also not sure that
			// manipulating the this pointer in this way is a good idea. What if you then try to use
			// this again in the context of D? Also, realloc might return a pointer to a diffent area
			// of memory or even NULL! I think this will try to free the original memory (bang!) and
			// assign new memory to p, which is a local so when it goes out of scope you'll leak memory
			void* p = realloc(reinterpret_cast<void*>(this), sizeof(C));
			new(p) C;
		}
		return n;
	}
	void Set(long n)
	{
		m_n = n;
	}
	long Get()
	{
		return m_n;
	}
protected:
	long m_count;
	long m_n;
};
 
 
int main(int argc, char* argv[])
{
	D* pD = new D;
	long n = pD->Increase();
	n = pD->Get(); 
	pD->Set(7);
	n = pD->Get();
	n = pD->Decrease();
	n = pD->Decrease(); 
	return 0;
}
Open in New Window
 
04.27.2008 at 09:52AM PDT, ID: 21449639

Rank