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:
- Constructor to get the
C*
pointer and store it in the improvided pointer-like class. - Destructor to remove the object heap-allocated
C
whenp
gets out of scope ofmain
function. - Overloaded
->
operator so thatp->Do();
will correctly invoke theC::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;
}
};
精彩评论