473,791 Members | 2,995 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
stelios xanthakis escribió:
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)).


Use a pointer, no magic required.

Regards.
Jul 19 '05 #31
Ragnar wrote:
...
When you get down to the shanties, everything has an address.
No. Only those entities that occupy storage (at least at conceptual
level) have addresses. Entities that don't occupy storage can't have
addresses.
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.
No. When the compiler sees the need to allocate storage for a reference,
then it is implemented as a pointer. When the compiler doesn't see the
need to allocate storage, reference is not implemented as a pointer and
has no place in the storage.
If you want to really understand references, then just
interface with a small assembly language program. All the mystique of
references will melt away.
While understanding of inner workings of the compiled program could be
very useful, it is important to know the difference between
language-level concepts and machine-level concepts.
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.
It doesn't necessary mean exactly that. This statement is ambiguous,
when taken out of context. I think that within the context of this
discussion everyone understands what is meant under "one cannot take the
address of the reference". It was explained in great detail in previous
replies.

Just like when C++ standard says that "object of array type cannot be
modified", we all understand what it really means. Although for an
unprepared reader it might sound like C++ standard prohibits, for
example, assignment to array's elements.
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.
Of course. "Label i" does not occupy storage. It doesn't have a address.
Labels do not have addresses anyway in C++.
Labels (as they were informally defined above) _can't_ have addresses in
any language. It has nothing to do with 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.


Not necessarily. In general case the compiler will be forced to
implement this reference as a pointer. In certain particular cases it
might be able to do perfectly fine without it.

--
Best regards,
Andrey Tarasevich

Jul 19 '05 #32
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.


Of course, one had better make sure the reference isn't bound to a derived
class before attempting that game.


Quite. And, in general, there's no way to know. Also, of course, this
nasssty treacherous trick requires that you know what constructor
parameters to pass to the placement new, and that the old object's
destructor not have side-effects that make the operation invalid
(like, for example, unlocking a mutex), and....

-Ron
Jul 19 '05 #33
Andrey Tarasevich wrote:

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.


It all depends on the motivatation:
http://www.afralisp.com/vbaa/unmain.htm

Jul 19 '05 #34
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:7B7sb.1252 67$ao4.386072@a ttbi_s51...
"Gary Labowitz" <gl*******@comc ast.net> wrote...
"Dave" <be***********@ yahoo.com> wrote in message
news:vr******** ****@news.super news.com...
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.


Yes, of course, but what I am saying is: Can you set up a class with a
reference member, initialize it when the object is created and then use it.
By creating a new object of that class anytime you want to dynamically
"assign" that reference it satisfies the OP's question. Doesn't it?
--
Gary
Jul 19 '05 #35
"Dave" <be***********@ yahoo.com> wrote in message news:<vr******* *****@news.supe rnews.com>...

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?


Could. First of all I think we should see differently references in
arguments and local/global reference variables. Most C++ books I've
seen say that local/global reference variables are of little use.

References are extremely useful in function arguments and return
value. It is a language feature I think that you cannot take the
address of a reference and that it there for our protection. For example
int foo (int&)
int bar ()
{
int i;
foo (i);
}

Here references guarantee that foo will not store the address of 'i'
in a place which will remain there *after* bar has returned, causing
lots of trouble.

Reference variables on the other hand are kind of "disabled" due to
the fact that they cannot be reassigned. The problem seems to be
just syntactical: How can you tell that this operation doesn't happen
to what the reference points to, but to the reference itself?
Right now the answer is: You can't. Use a pointer instead.

Allowing to "dereferenc e" references gives more interesting possibilities
(for example: dereference (ri == rj), to see that references point to
same thing), and more ways to screw up (for example: delete dereference ri).
So one factor is whether we believe that the people using the language
have consciousness of what they're doing and they're not drunken. :)

Anyway, I do agree that the comitee thinks about those things much deeper.
Discussions in newsgroups may give them interesting ideas though.
Stelios
Jul 19 '05 #36
On Wed, 12 Nov 2003 02:34:46 -0800, stelios xanthakis wrote:
int foo (int&)
int bar ()
{
int i;
foo (i);
}

Here references guarantee that foo will not store the address of 'i' in
a place which will remain there *after* bar has returned, causing lots
of trouble.
Eh?

void store_pointer(i nt*);

int foo (int& x) {
store_pointer(& x);
}
Allowing to "dereferenc e" references gives more interesting
possibilities (for example: dereference (ri == rj), to see that
references point to
if (&ri == &rj) {
printf("ri and rj reference the same object\n");
}
same thing), and more ways to screw up (for example: delete dereference
ri). So one factor is whether we believe that the people using the
language have consciousness of what they're doing and they're not
drunken. :)


The point of references is that you can conveniently make a function that
is called without performing copying of it's parameters and can modify the
actual parameters (instead of a copy of them) without having to muck about
with pointer syntax.

compare:

void add42(int* value) {
*value +=42;
}

void add42(int& value) {
value += 42;
}

Now if the function was a little more advanced perhaps with several
parameters that shall be modified using a reference instead of a pointer
could make the code a lot clearer.

--
NPV

"the large print giveth, and the small print taketh away"
Tom Waits - Step right up

Jul 19 '05 #37
"Gary Labowitz" <gl*******@comc ast.net> wrote...
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:7B7sb.1252 67$ao4.386072@a ttbi_s51...
"Gary Labowitz" <gl*******@comc ast.net> wrote...
[...]
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.


Yes, of course, but what I am saying is: Can you set up a class with a
reference member, initialize it when the object is created and then use

it. By creating a new object of that class anytime you want to dynamically
"assign" that reference it satisfies the OP's question. Doesn't it?


I don't think so. Every time you instantiate such a class, you create
a _new_ reference, not _reuse_ the same one.

There is no need to play with words (and use double quotes) when it
comes to the language. Especially there is no need to substitute one
term with another when both are used with different meanings:
"an initialisation" is never "an assignment" and vice versa (you may
remove the double quotes and you will still have the true statement).

Victor

Jul 19 '05 #38

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
9669
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9515
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,...
1
10155
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
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
6776
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
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
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.