473,791 Members | 3,137 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assigning to references

Hello all,

Please consider the code below. It is representative of a problem I am
having.

foo_t needs to contain a bar_t which is a class without a copy constructor
or operator=. It is not within my control to change bar_t. Furthermore, I
need to be able to update the contained bar_t at runtime (hence the
set_bar() method seen below).

The code *almost* works. Here's the problematic line:

void set_bar(bar_t &b) {bar = b;}

This fails to compile with a message that operator= is inaccessible. Why
should this be a problem since I'm trying to assign to a reference? I only
want my reference member to refer to a new object; I'm not actually copying
an object. Why should operator= come into play? After all, I can pass a
reference to bar_t as a parameter just fine even though the copy constructor
is also inaccessible.

Assuming though that my compiler is behaving properly, I won't be able to
take this approach regardless of whether or not I understand why it's
disallowed. With that in mind, what's my next best alternative to create an
effect similar to what the code below attempts?

Thanks!
Dave

P.S. In case anyone is tempted to ask "What are you trying to do?", bar_t
corresponds to ofstream and foo_t corresponds to one of my application
classes. I need to contain an ofstream for logging, and I need to be able
to change that stream occassionally (i.e. start logging to a different
place).

class bar_t
{
public:
bar_t() {}

private:
bar_t(const bar_t &); // Leave undefined
bar_t &operator=(cons t bar_t &); // Leave undefined
};

class foo_t
{
public:
foo_t(): bar(initial_bar ) {}
void set_bar(bar_t &b) {bar = b;}

private:
bar_t initial_bar; // Must come *before* member bar as it is used to
initialize bar.
bar_t &bar;
};

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
Jul 19 '05
37 3978
Dave wrote:
...
I had sent an earlier post that for some reason didn't get through (and some
of you may have noticed that for some reason, my original post got posted
twice; sorry about that...).
...
You cross-posted your first post to 'comp.lang.c++. moderated', which is
as pre-moderated conference. It takes quite some time for your post to
go through the moderation queue and appear in the conference (much
longer than in case of non-moderated conference as 'comp.lang.c++' ). The
important detail here is that such post will not appear in _any_ of the
conferences you sent it to until it is approved by
'comp.lang.c++. moderated'. That's why your second post on the same
subject (sent to 'comp.lang.c++' only) appeared here much sooner.
Is there some sort of treacherous trick that would allow us to get the
address of the reference (as opposed to the referent)? Is a reference even
guaranteed to *have* an address, or might it be just a simple compile-time
alias for the referent?


In general case the reference is not guaranteed to occupy any memory,
which means that in general case it doesn't have an address.

In some other particular practical cases the reference will be
implemented as "a pointer in disguise" and will occupy memory. In such
cases it is probably possible to gain access to the reference itself and
modify it, but i'm pretty sure that even the most hardcore language
"hackers" will agree that practical value of such technique is zero or
even less.

--
Best regards,
Andrey Tarasevich

Jul 19 '05 #21
Ron
> One poster mentioned the possibility of re-binding a reference by destroying
the old rerferent with a manual destructor call and then using placement new
to construct the new object in the same memory. Though ill-advised, this
does sound like a standard-conforming way to do it.
Yeah, it's conformant -- and yeah, it's ill-advised. See s.3.8(7) for
what the Standard does with it.
This got me to wondering...

Is there some sort of treacherous trick that would allow us to get the
address of the reference (as opposed to the referent)? Is a reference even
guaranteed to *have* an address, or might it be just a simple compile-time
alias for the referent? I'd be interested to here any thoughts on all of
this...


References don't have addresses. s.8.3.2(4)("The re shall be no
references to references, no arrays of references, and no pointers to
references.") References are merely aliases for the things to which
they're bound.

-Ron
Jul 19 '05 #22

"Ron" <rc****@ictv.co m> wrote in message news:c6******** *************** ***@posting.goo gle.com...
One poster mentioned the possibility of re-binding a reference by destroying
the old rerferent with a manual destructor call and then using placement new
to construct the new object in the same memory. Though ill-advised, this
does sound like a standard-conforming way to do it.


Yeah, it's conformant -- and yeah, it's ill-advised. See s.3.8(7) for
what the Standard does with it.


Of course, one had better make sure the reference isn't bound to a derived
class before attempting that game.
Jul 19 '05 #23
Dave wrote:
Is there some sort of treacherous trick that would allow us to get the
address of the reference (as opposed to the referent)? Is a reference even
guaranteed to *have* an address, or might it be just a simple compile-time
alias for the referent?

Andrey Tarasevich <an************ **@hotmail.com> wrote In general case the reference is not guaranteed to occupy any memory,
which means that in general case it doesn't have an address.

In some other particular practical cases the reference will be
implemented as "a pointer in disguise" and will occupy memory. In such
cases it is probably possible to gain access to the reference itself and
modify it, but i'm pretty sure that even the most hardcore language
"hackers" will agree that practical value of such technique is zero or
even less.


Just for grins, I did this. I created a class with a member that was
a reference, in such a way that I could figure out the address of the
reference. Then I modified the value in that reference and observed
that the reference had indeed been "re-seated."

Take it for what little it's worth. I am 100% certain that this is
not standard-compliant, because I had to exceed the bounds of an
array in order to find that address. Note that even though I set up
a situation in which I knew that the compiler did HAVE to create a
"pointer in disguise," there was still a huge risk that it wouldn't
work right (or it won't work right in future versions of the same
compiler, or that it won't even work in this version with different
compile options). Essentially what I did was to change the value in
some memory that I wasn't supposed to touch. The compiler may have
assumed that this memory couldn't have been changed, and used this
to "optimize" the code -- in which case, had my program run a
little bit longer, it conceivably could have broken.

This is NOT something I plan to put on a resume. In fact, I wish I
hadn't done it. I feel dirty now, like I need a shower. The truth
is, I never even did it -- I don't know who figured out my Google
password, but it wasn't me who even said this.

Please, Dave, I beg you -- don't bother figuring out how it's done.
Forget the whole idea. Just use pointers like everyone else that
can be proud of their code.
Jul 19 '05 #24
Andrey Tarasevich <an************ **@hotmail.com> wrote in message news:<vq******* *****@news.supe rnews.com>...
Dave wrote:
Is there some sort of treacherous trick that would allow us to get the
address of the reference (as opposed to the referent)? Is a reference even
guaranteed to *have* an address, or might it be just a simple compile-time
alias for the referent?


In general case the reference is not guaranteed to occupy any memory,
which means that in general case it doesn't have an address.

In some other particular practical cases the reference will be
implemented as "a pointer in disguise" and will occupy memory. In such
cases it is probably possible to gain access to the reference itself and
modify it, but i'm pretty sure that even the most hardcore language
"hackers" will agree that practical value of such technique is zero or
even less.


Hi.

I've been thinking about references (lwc) and I came up with this
idea in order to be able to change their value:

Something like an unary pseudo-operator called "dereferenc e (EXPR)".
For the EXPR in the parentheses, references will be taken as
pointers (compiler will not magically convert them to (*var)).

For example:

int i, j;
int &ri = i, &rj = j;

// same as i=3
ri = 3;

// same as i=j
ri = rj;

// dereference. ri points to same thing with rj
dereference (ri = rj);

// make rj point to i
dereference (rj) = &i;

This is very easy to implement in a compiler, provided that
references are implemented as "pointers in disguise" indeed.

Hmmm. Good, average or terrible idea?

stelios.
Jul 19 '05 #25
"Dave" <be***********@ yahoo.com> wrote :
One poster mentioned the possibility of re-binding a reference by destroying
the old rerferent with a manual destructor call and then using placement new
to construct the new object in the same memory. Though ill-advised, this
does sound like a standard-conforming way to do it. This got me to
wondering...

Is there some sort of treacherous trick that would allow us to get the
address of the reference (as opposed to the referent)? Is a reference even
guaranteed to *have* an address, or might it be just a simple compile-time
alias for the referent? I'd be interested to here any thoughts on all of
this...


When you get down to the shanties, everything has an address. A C++
reference is usually implemented as a pointer. And if i restrict my
discussion to the IA-32 architecture, then a reference IS implemented
as a pointer. If you want to really understand references, then just
interface with a small assembly language program. All the mystique of
references will melt away.

References are a very usefull HLL tool. They support pass-by-address
semantics, with the pass-by-value syntactics. They are aliases and
lvalues. And one does not have to deal with the *muck* of the pointers
(though, some, like Yours Truly like wallowing in that sort of muck).
But this hiding of the pointer syntax with the nice references, puts
restrictions on you (within the C++ type system). Some might even say
that it is just a syntactic sugar.

Statement like 'one cannot take the address of the reference' are a
bit misleading. I remember reading this in Herb Schildt's C++: The
complete reference. This, if one thinks in C++, implies that one
cannot apply the address of operator, &, to references, which is
incorrect. A semantically precise statement is that references are
aliases, and that all the operations on a reference variable are
actually done on the referend (which also answers your original
question). So when you take the address of a reference, you get the
address of the referend, which is semanticallly precise.

Think of a reference as a label. So if you declare a variable, say int
i, and you want the address of i, then what you get is the address of
the object pointed to by i (the int), not of the label i. Labels do
not have addresses anyway in C++. So now if you declare a reference,
say int & ri = i; then think that ri is another label. And to be
consistent, you can't get the address of this new label any more than
you can of the old. This new label has some additional properties, but
that is another story.

In case you can only use C++, declare a class which has only one
member: a reference, and no virtual functions. This reference is
initialised from the initialisation list in the ctor. Then the adress
of the class will be the address of the reference. Use some old
C-style casts, to get what you want.

--
Ragnar
Jul 19 '05 #26
> Hi.

I've been thinking about references (lwc) and I came up with this
idea in order to be able to change their value:

Something like an unary pseudo-operator called "dereferenc e (EXPR)".
For the EXPR in the parentheses, references will be taken as
pointers (compiler will not magically convert them to (*var)).

For example:

int i, j;
int &ri = i, &rj = j;

// same as i=3
ri = 3;

// same as i=j
ri = rj;

// dereference. ri points to same thing with rj
dereference (ri = rj);

// make rj point to i
dereference (rj) = &i;

This is very easy to implement in a compiler, provided that
references are implemented as "pointers in disguise" indeed.

Hmmm. Good, average or terrible idea?

stelios.


On the surface, it does sound like a useful idea. It would be nice to be
able to re-bind a reference. Although, until a lot of thought was applied,
it would leave me uneasy simply because C++ is a very, very rich language
and the different features of the language sometimes interact in surprising
or non-apparent ways. Might it be that adding the ability to re-bind a
reference might cause other problems in the language? Maybe there's nothing
to what I'm saying, but the cautious side of me says that to mess with
something as complex as C++ requires a *lot* of due dilligence and
forethought. Even then, something might be missed! But barring any such
deep ramifications, I would indeed like such a feature to be available! Now
getting the standards committee to consider it might be a bit of a
challenge!!!
Jul 19 '05 #27

"Ragnar" <at*******@yaho o.com> wrote in message
news:9c******** *************** ***@posting.goo gle.com...
"Dave" <be***********@ yahoo.com> wrote :
One poster mentioned the possibility of re-binding a reference by destroying the old rerferent with a manual destructor call and then using placement new to construct the new object in the same memory. Though ill-advised, this does sound like a standard-conforming way to do it. This got me to
wondering...

Is there some sort of treacherous trick that would allow us to get the
address of the reference (as opposed to the referent)? Is a reference even guaranteed to *have* an address, or might it be just a simple compile-time alias for the referent? I'd be interested to here any thoughts on all of this...


When you get down to the shanties, everything has an address. A C++
reference is usually implemented as a pointer. And if i restrict my
discussion to the IA-32 architecture, then a reference IS implemented
as a pointer. If you want to really understand references, then just
interface with a small assembly language program. All the mystique of
references will melt away.

References are a very usefull HLL tool. They support pass-by-address
semantics, with the pass-by-value syntactics. They are aliases and
lvalues. And one does not have to deal with the *muck* of the pointers
(though, some, like Yours Truly like wallowing in that sort of muck).
But this hiding of the pointer syntax with the nice references, puts
restrictions on you (within the C++ type system). Some might even say
that it is just a syntactic sugar.

Statement like 'one cannot take the address of the reference' are a
bit misleading. I remember reading this in Herb Schildt's C++: The
complete reference. This, if one thinks in C++, implies that one
cannot apply the address of operator, &, to references, which is
incorrect. A semantically precise statement is that references are
aliases, and that all the operations on a reference variable are
actually done on the referend (which also answers your original
question). So when you take the address of a reference, you get the
address of the referend, which is semanticallly precise.

Think of a reference as a label. So if you declare a variable, say int
i, and you want the address of i, then what you get is the address of
the object pointed to by i (the int), not of the label i. Labels do
not have addresses anyway in C++. So now if you declare a reference,
say int & ri = i; then think that ri is another label. And to be
consistent, you can't get the address of this new label any more than
you can of the old. This new label has some additional properties, but
that is another story.

In case you can only use C++, declare a class which has only one
member: a reference, and no virtual functions. This reference is
initialised from the initialisation list in the ctor. Then the adress
of the class will be the address of the reference. Use some old
C-style casts, to get what you want.

--
Ragnar


This idea, as suggested by you and one other poster, is interesting! I
think I'll try it for kicks, but as was also stated in this thread, it's not
going on my resume (or in any production code)!!!

Thanks for the thoughts everyone!
Jul 19 '05 #28
"Dave" <be***********@ yahoo.com> wrote in message
news:vr******** ****@news.super news.com...
Hi.

I've been thinking about references (lwc) and I came up with this
idea in order to be able to change their value:

Something like an unary pseudo-operator called "dereferenc e (EXPR)".
For the EXPR in the parentheses, references will be taken as
pointers (compiler will not magically convert them to (*var)).

For example:

int i, j;
int &ri = i, &rj = j;

// same as i=3
ri = 3;

// same as i=j
ri = rj;

// dereference. ri points to same thing with rj
dereference (ri = rj);

// make rj point to i
dereference (rj) = &i;

This is very easy to implement in a compiler, provided that
references are implemented as "pointers in disguise" indeed.

Hmmm. Good, average or terrible idea?

stelios.
On the surface, it does sound like a useful idea. It would be nice to be
able to re-bind a reference. Although, until a lot of thought was

applied, it would leave me uneasy simply because C++ is a very, very rich language
and the different features of the language sometimes interact in surprising or non-apparent ways. Might it be that adding the ability to re-bind a
reference might cause other problems in the language? Maybe there's nothing to what I'm saying, but the cautious side of me says that to mess with
something as complex as C++ requires a *lot* of due dilligence and
forethought. Even then, something might be missed! But barring any such
deep ramifications, I would indeed like such a feature to be available! Now getting the standards committee to consider it might be a bit of a
challenge!!!


But I take it you can put a reference as a data member of a class and in
creating an instance set the reference using a parameter.
This would satisfy assignment of a reference at runtime, wouldn't it?
--
Gary
Jul 19 '05 #29
"Gary Labowitz" <gl*******@comc ast.net> wrote...
"Dave" <be***********@ yahoo.com> wrote in message
news:vr******** ****@news.super news.com...
Hi.

I've been thinking about references (lwc) and I came up with this
idea in order to be able to change their value:

Something like an unary pseudo-operator called "dereferenc e (EXPR)".
For the EXPR in the parentheses, references will be taken as
pointers (compiler will not magically convert them to (*var)).

For example:

int i, j;
int &ri = i, &rj = j;

// same as i=3
ri = 3;

// same as i=j
ri = rj;

// dereference. ri points to same thing with rj
dereference (ri = rj);

// make rj point to i
dereference (rj) = &i;

This is very easy to implement in a compiler, provided that
references are implemented as "pointers in disguise" indeed.

Hmmm. Good, average or terrible idea?

stelios.


On the surface, it does sound like a useful idea. It would be nice to be able to re-bind a reference. Although, until a lot of thought was

applied,
it would leave me uneasy simply because C++ is a very, very rich language and the different features of the language sometimes interact in

surprising
or non-apparent ways. Might it be that adding the ability to re-bind a
reference might cause other problems in the language? Maybe there's

nothing
to what I'm saying, but the cautious side of me says that to mess with
something as complex as C++ requires a *lot* of due dilligence and
forethought. Even then, something might be missed! But barring any such deep ramifications, I would indeed like such a feature to be available!

Now
getting the standards committee to consider it might be a bit of a
challenge!!!


But I take it you can put a reference as a data member of a class and in
creating an instance set the reference using a parameter.
This would satisfy assignment of a reference at runtime, wouldn't it?


No. It's not "assignment ". It's "initialisation ". Look it up.

Victor
Jul 19 '05 #30

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

Similar topics

5
6411
by: gtz669 | last post by:
I have a class which I am using for data stroage. I declare an instance of that class in my main class which is running my java applet. I Iassign it a value in the init () function and it works fine but when I try to do the same assignment later on, it restults in a NullPointerException and I can not figure this out. Could someone please help. Thanks. Here's the code: public class A extends java.applet.Applet
5
3651
by: Dave | last post by:
Hello all, Please consider the code below. It is representative of a problem I am having. foo_t needs to contain a bar_t which is a class without a copy constructor or operator=. It is not within my control to change bar_t. Furthermore, I need to be able to update the contained bar_t at runtime (hence the set_bar() method seen below).
14
74902
by: Eric Bantock | last post by:
Very basic question I'm afraid. Once an array has been declared, is there a less tedious way of assigning values to its members than the following: myarray=8; myarray=3; myarray=4; myarray=0; myarray=0; myarray=1; myarray=8;
8
13722
by: Woody Splawn | last post by:
Lets say I have a winform that is populated with a dataset. The dataset and data table may have several rows in it. Lets say I am looking at the winform and I want to assign a value to a certain column in the associated datatable. Lets say there are 10 rows in the table and I am on row 5, and I want to assign the value to row 5, but I don't know that I am on row 5. Anyway, my method for assigning the value to the field would be: Dim Dt...
20
7013
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt = document.getElementById('hometab'); Has anyone ever seen anything like this before, or am I dreaming?
2
2584
by: Bernie Hunt | last post by:
I'm having trouble assigning the reportsource value at run time. I'm running a test setup, one form with only a Crystal Viewer, called cvwMail. My report is called CustomersBasic.rpt and it draws directly from the TradeWinds.MDB test database. If I use Me.cvwMain.ReportSource = "J:\Learning\CMP 214\Crystal Test\CrystalTest \CustomersBasic.rpt to point to the file directly it works.
7
1762
by: Daniel | last post by:
I am baffled. According to the C++ faq lite it is ok to use a reference as an lvalue, and the subscript operator returns a reference. However, when I run this program, it crashes! I will go set up a different compiler and try again while I'm waiting for a reply, but I'm really curious about why this is happening. I'm using the mingw compiler that came with dev-c++ on an up to date Windows 2000 box. Any help would be greatly appreciated,...
8
4547
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
Hello, Newsgroupians: I have a large class with a lot of member variables. I also have a function in the class that I would like to change ALL Of the member variables. I am trying to assign "this" to the result, but I always get the error message, "Cannot assign to '<this>' because it is read-only." I've been searching on the Internet, and I notice some C# code is violating this rule. Perhaps their code is wrong.
10
4025
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
10207
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...
0
9995
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
9029
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7537
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5431
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4110
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
3718
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2916
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.