简体   繁体   中英

C++ pointers and classes

Trying to solve this question for the last 45 minutes, but couldn't figure out the what I'm suppose to do. Here's the question.

class C; //forward declaration
class Cpointer {
 public:

};

class C { //do not modify
   int i;
  public:
   C(int _i=0) : i(_i) {}
   Cpointer operator& () { return Cpointer(this); }
   void Do() { std::cout << "i=" << i << std::endl; }
 };


 int main() {
   Cpointer p (new C(100));
   p->Do();
 }

Complete class Cpointer so that the code compiles. Make sure there are no memory leaks.

As I understand CPointer class takes a C class as a parameter for the constructor. When I try the below code I'm getting a compiler error telling that "use of undefined type C" inside the CPointer's Do function.

class Cpointer
{
 C* mCptr;
   public:
  Cpointer(C* cptr) : mCptr(cptr){}
  void Do()
  {
    //mCptr->Do();
  }
};

I feel slightly uneasy posting solution but since you say it's not a homework... Here it is:

class Cpointer {
    C* ptr;
    public:
        Cpointer(C* c) : ptr(c) { }
        ~Cpointer() { delete ptr; }
        C* operator->() { return ptr; }
};

There are three points here:

  1. Constructor to get the C* pointer and store it in the improvided pointer-like class.
  2. Destructor to remove the object heap-allocated C when p gets out of scope of main function.
  3. Overloaded -> operator so that p->Do(); will correctly invoke the C::Do method.

Basically, what you were asked to implement is a partial functionality of the standard auto_ptr class.

Given the way Cpointer is used in main(), it has to be implemented like this:

class Cpointer
{
private:
    C* c:
public:
    Cpointer(C* _c) : c(_c) {}
    ~Cpointer() { delete c; }
    C* operator ->() { return c; }
};

The problem is that Cpointer is also used by C's overriden '&' operator, and this kind of implementation will not work for that usage. Memory corruption will occur, especially if the C instance is declared on the stack (which is when an overriden '&' operator is usually needed). To really make this work correctly, C would have to be modified, either to stop using Cpointer, or to contain a reference count that Cpointer manages. Either way violates the "do not modify" restriction on C.

so that it compiles, and doesn't leak? ok.

class Cpointer
{
   public:
   Cpointer(C* c)
   {  delete c; }
  void Do()
  {  }
   Cpointer* operator ->()
   { return this; }
};
class C; //forward declaration
class Cpointer {
 public:
 C* mptr;

 Cpointer(C *cptr){
     mptr = cptr;
 }

 ~Cpointer(){
     delete mptr;
 }

 C* operator->() const {
     return mptr;
 }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM