W
Whitney Kew
Hello,
I have a question regarding type conversion operators. Let's say I
have a simple (nonsensical) class as follows:
class MakeNewInt
{
private:
int* _n;
// By the way, because of the type conversion operator, a
// compiler might not catch an accidental deletion of a
// stack instance - i.e., "delete MakeNewInt(123)" - so,
// add a private operator void*() declaration.
operator void*();
public:
operator int*() const
{
return _n;
}
MakeNewInt(int n) : _n(new int(n)) {}
~MakeNewInt()
{
delete _n;
}
};
Let's also say that I have a method as follows:
void f(int* n)
{
int* q = n;
// Can do other things with q...
}
If I then invoke f() in a main() as such....
int main()
{
f(MakeNewInt(123)); // OK
return 0;
}
....everything is fine; inside f(), I can operate on the pointer q,
knowing that the destructor of MakeNewInt() won't be called until I
exit f().
If, however, I invoke MakeNewInt and attempt to store the result in a
local variable, as such....
int main()
{
int* n = MakeNewInt(123); // n is garbage
return 0;
}
....the destructor of MakeNewInt() has already been called as soon as I
reach the "return 0;" line, and thus the pointer n points to garbage.
Is there anything I can do to allow a caller to use my MakeNewInt class
in this fashion?
Thanks!
Whitney Kew
Software Engineer
I have a question regarding type conversion operators. Let's say I
have a simple (nonsensical) class as follows:
class MakeNewInt
{
private:
int* _n;
// By the way, because of the type conversion operator, a
// compiler might not catch an accidental deletion of a
// stack instance - i.e., "delete MakeNewInt(123)" - so,
// add a private operator void*() declaration.
operator void*();
public:
operator int*() const
{
return _n;
}
MakeNewInt(int n) : _n(new int(n)) {}
~MakeNewInt()
{
delete _n;
}
};
Let's also say that I have a method as follows:
void f(int* n)
{
int* q = n;
// Can do other things with q...
}
If I then invoke f() in a main() as such....
int main()
{
f(MakeNewInt(123)); // OK
return 0;
}
....everything is fine; inside f(), I can operate on the pointer q,
knowing that the destructor of MakeNewInt() won't be called until I
exit f().
If, however, I invoke MakeNewInt and attempt to store the result in a
local variable, as such....
int main()
{
int* n = MakeNewInt(123); // n is garbage
return 0;
}
....the destructor of MakeNewInt() has already been called as soon as I
reach the "return 0;" line, and thus the pointer n points to garbage.
Is there anything I can do to allow a caller to use my MakeNewInt class
in this fashion?
Thanks!
Whitney Kew
Software Engineer