I'm trying to write a smart pointer class for an int variable but I've gotten a little stuck. Firstly, to declare a smart pointer to an int, I MUST use this line of code (As seen in the main method below):
smart_pointer s = new int();
To do this, I try to overload the "=" operator and set a pointer to an int (called "value" in the smart_pointer class) to the address of this new int. However, I get this error:
"conversion from ‘int*’ to non-scalar type ‘smart_pointer’ requested"
What am I doing wrong? I thought "new int()" returned a memory address which I could set the smart_pointer's int pointer to by overloading the "=" sign...
i.e., you should write a constructor instead (or perhaps, in addition to overloading operator= since you should also define or disable the copy constructor and copy assignment operator)
C + C++ Compiler: MinGW port of GCC
Build + Version Control System: SCons + Bazaar
Looking at your implementation, you might be interested in just using auto_ptr instead.
If you have access to boost or C++0x, then you could look into unique_ptr and shared_ptr.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Last edited by monarch_dodra; August 17th, 2011 at 05:31 AM.
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Remember to make the constructor explicit. Inadvertently placing a pointer into an object that claims ownership of the pointer's life is one of the last things you want to do.
[EDIT]Whilst were on the subject, having "smart_pointer &operator=(int *val)" and being able to write "smart_pointer s = new int();" are both very bad ideas, for the same reason.
You'll want a named member function to do that.
PS: There is a flaw in your operator= implementation: What if your smart_pointer already had a value?
Is your question related to IO?
Read this C++ FAQ LITE article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Bookmarks