473,886 Members | 2,373 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Storing pointer to instance of class with type conversion operator

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(12 3)); // 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

Jul 22 '05 #1
10 2038
Whitney Kew wrote:
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(12 3)); // 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?


int * const & n = MakeNewInt(123) ;

The object here is bound to a reference to const and shall exist for as
long as the reference exists.

V
Jul 22 '05 #2
Unfortunately, that doesn't work; n points to a pointer that points to
garbage as soon as the statement completes. Plus, I don't want the
caller to have to remember something like that, since I don't
necessarily have control over what the caller writes. I was hoping
that there was some way that I could modify the MakeNewInt class, while
preserving the type conversion operator functionality, so that a caller
could safely make the following call:
int* n = MakeNewInt(123) ;

Thanks,
Whitney

Jul 22 '05 #3
Whitney Kew wrote:
Unfortunately, that doesn't work; n points to a pointer that points to
garbage as soon as the statement completes.
Your compiler might be broken, then. Binding to a const reference should
keep the temporary around well past the declaration statement, AFAIUI.

Try

int * const & n(MakeNewInt(12 3));

although AFAIK it shouldn't make any difference.
Plus, I don't want the
caller to have to remember something like that, since I don't
necessarily have control over what the caller writes. I was hoping
that there was some way that I could modify the MakeNewInt class, while
preserving the type conversion operator functionality, so that a caller
could safely make the following call:
int* n = MakeNewInt(123) ;


When is the object going to be destroyed, then? Something has to exist
that defines the lifetime of that temporary. In C++ there are three
different limits for a temporary lifetime. Generally it is the full
expression. Then the initialisation (with which you're struggling). And
then there's binding to a const reference. No matter what you do in your
class, you won't be able to change how the language is specified.

You might want to rethink the need for your users to do such a stupid
thing as holding onto a pointer obtained from a temporary object.

V
Jul 22 '05 #4
Hm, strange. I tried your suggestion of:

int * const & n(MakeNewInt(12 3));

.... and my compiler couldn't even build it.

OK, let me ask another question: My intended use of this class is for
the callers to use it as in the first case...

f(MakeNewInt(12 3));

.... Could I somehow prevent the user from using it in the second case;
in other words, at compile time, prevent the user from storing a
temporary object?

Thanks much!
Whitney

Jul 22 '05 #5
Unfortunately, that doesn't work; n points to a pointer that points to
garbage as soon as the statement completes. Plus, I don't want the
caller to have to remember something like that, since I don't
necessarily have control over what the caller writes. I was hoping
that there was some way that I could modify the MakeNewInt class, while
preserving the type conversion operator functionality, so that a caller
could safely make the following call:
int* n = MakeNewInt(123) ;

Thanks,
Whitney

Jul 22 '05 #6
Do you need to hold on to the pointer in your creating class? If that is a
requirement, then implement the pointer with reference counting, if it isn't
a requirement, then make a static create method returning a std::auto_ptr
(implicitly passing pointer ownership to the caller).

ad
"Whitney Kew" <wk************ @yahoo.com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
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(12 3)); // 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

Jul 22 '05 #7
Whitney Kew wrote:
Hm, strange. I tried your suggestion of:

int * const & n(MakeNewInt(12 3));

... and my compiler couldn't even build it.

OK, let me ask another question: My intended use of this class is for
the callers to use it as in the first case...

f(MakeNewInt(12 3));

... Could I somehow prevent the user from using it in the second case;
in other words, at compile time, prevent the user from storing a
temporary object?


No. Just like you can't prevent a memory leak in the case

f(new int(123));

(which is probably what you're trying to do). There are some things in
the language that every programmer has to know, and it's not really our
responsibility to provide fool-proof methods for avoiding them. If your
users are so inclined to make such mistakes like holding onto invalid
pointers, they should be programming in Java instead.

V
Jul 22 '05 #8
There are smart pointer templates you should take a look at - search google,
or look at the Boost or Loki libraries - one form (NoCopy Policy in Loki)
disallows copy and assignment of the pointer variable - you are forced to
use the pointer through an accessor of the containing object. There is no
other way to access the underlying pointer.

You could implement it yourself - but someone's already done it so why
bother?
"Whitney Kew" <wk************ @yahoo.com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.com.. .
Hm, strange. I tried your suggestion of:

int * const & n(MakeNewInt(12 3));

... and my compiler couldn't even build it.

OK, let me ask another question: My intended use of this class is for
the callers to use it as in the first case...

f(MakeNewInt(12 3));

... Could I somehow prevent the user from using it in the second case;
in other words, at compile time, prevent the user from storing a
temporary object?

Thanks much!
Whitney

Jul 22 '05 #9
"Whitney Kew" <wk************ @yahoo.com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.com.. .
Hm, strange. I tried your suggestion of:

int * const & n(MakeNewInt(12 3));

... and my compiler couldn't even build it.

OK, let me ask another question: My intended use of this class is for
the callers to use it as in the first case...

f(MakeNewInt(12 3));

... Could I somehow prevent the user from using it in the second case;
in other words, at compile time, prevent the user from storing a
temporary object?


As far as the class's clients are concerned, what is the difference between
the class you've defined and this one?

class MakeNewInt
{
private:
int _n;
operator void*();
public:
operator int*() const
{
return &_n;
}
MakeNewInt(int n) : _n(n) {}
};

I can't see any difference between them except that your version requires a
lot more work for no benefit (your version needs a copy constructor,
assignment operator and destructor, but mine doesn't). If you agree that the
use of 'new' in your version is redundant, what memory management benefits
could it offer?

DW

Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2589
by: Alfonso Morra | last post by:
I have written the following code, to test the concept of storing objects in a vector. I encounter two run time errors: 1). myClass gets destructed when pushed onto the vector 2). Prog throws a "SEGV" when run (presumably - attempt to delete deleted memory. Please take a look and see if you can notice any mistakes I'm making. Basically, I want to store classes of my objects in a vector. I also have three further questions:
67
4506
by: Ike Naar | last post by:
Hi, Asking your advice on the following subject: Suppose I want to find out whether a given pointer (say, p) of type *T points to an element of a given array (say, a) of type T. A way to achieve this would be a linear search through the array: int ptrInArrSafe(T *p,T *a,int max) /* check whether p points to an element of a */
28
2426
by: Wonder | last post by:
Hello, I'm confused by the pointer definition such as int *(p); It seems if the parenthesis close p, it defines only 3 integers. The star is just useless. It can be showed by my program: int main() {
4
1085
by: Tommo | last post by:
I want to have my own class as a key in the STL map. Can anyone tell me what operators i need to override?? I think its the < operator but I think I may be missing something else
53
4594
by: Tomás | last post by:
Some programmers treat arrays just like pointers (and some even think that they're exactly equivalent). I'm going to demonstrate the differences. Firstly, let's assume that we're working on a platform which has the following properties: 1) char's are 8-Bit. ( "char" is synomonous with "byte" ). 2) int's are 32-Bit. ( sizeof(int) == 4 ). 3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).
13
2112
by: Protoman | last post by:
Here's a non intrusive reference counting smart pointer class I'm working on; I keep getting a "22 C:\Dev-Cpp\SmrtPtr.hpp ISO C++ forbids declaration of `SmrtPtrDB' with no type" error. Code: SmrtPtr.hpp #pragma once
42
5375
by: xdevel | last post by:
Hi, if I have: int a=100, b = 200, c = 300; int *a = {&a, &b, &c}; than say that: int **b is equal to int *a is correct????
6
2917
by: Lighter | last post by:
How to read "The lvalue-to-rvalue, array-to-pointer, and function-to- pointer standard conversionsare not applied to the left expressions"? In 5.18 Comma operator of the C++ standard, there is a rule: "The lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard conversionsare not applied to the left expressions" I could not understand what the rule means. I also searched the web and the groups and got nothing.
5
4673
by: Tim Frink | last post by:
Hi, I'm experimenting with function pointers and found two questions. Let's assume this code: 1 #include <iostream> 2 class A; 3 4 //////////////////////////////////////////// 5 class B
0
9799
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10770
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10873
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10430
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7141
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5809
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6010
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4632
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4236
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.