473,789 Members | 2,781 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reference and pointer-reference

Hi,

Recently i came across a functiion declaration as below

void f(char *&a);

Nowhere i have come across this style. I understand, passing by
reference is always better(to avoid copying), that too added with
const like

void f(const std::string &a); //since it was char *a, i assume it to
be a string

This i came across in the book "Secrets of C++ Masters". Though this
book is old, i just wanted to know what it speaks of. I do not know
whether this is still accepted or was a part of pre-standard c++. I
tried a toy program with a function like this. It did compile fine and
executed successfully. As per the book, this style prevents pointer
copy(address copy) - is that true? atleast in c++. Pls advice.

Thanks,
Balaji.
Dec 24 '07 #1
4 1535
ka************* ******@gmail.co m wrote:
Hi,

Recently i came across a functiion declaration as below

void f(char *&a);

Nowhere i have come across this style. I understand, passing by
reference is always better(to avoid copying),
I wouldn't say "always".
that too added with const like

void f(const std::string &a); //since it was char *a, i assume it to
be a string

This i came across in the book "Secrets of C++ Masters". Though this
book is old, i just wanted to know what it speaks of. I do not know
whether this is still accepted or was a part of pre-standard c++. I
tried a toy program with a function like this. It did compile fine and
executed successfully. As per the book, this style prevents pointer
copy(address copy) - is that true?
Yes. In the above function, the pointer is passed by reference. That way, f
can change the pointer value. It could e.g. allocate dynamic memory and
assign its address to a, which refers to the variable that was passed by
the caller. If the paramter was just a char*, f()'s changes to it would
only be local to the function, since a is just a copy of the pointer that
was passed by the caller.
Dec 24 '07 #2
On 2007-12-24 12:14, ka************* ******@gmail.co m wrote:
Hi,

Recently i came across a functiion declaration as below

void f(char *&a);

Nowhere i have come across this style. I understand, passing by
reference is always better(to avoid copying), that too added with
const like

void f(const std::string &a); //since it was char *a, i assume it to
be a string

This i came across in the book "Secrets of C++ Masters". Though this
book is old, i just wanted to know what it speaks of. I do not know
whether this is still accepted or was a part of pre-standard c++. I
tried a toy program with a function like this. It did compile fine and
executed successfully. As per the book, this style prevents pointer
copy(address copy) - is that true? atleast in c++. Pls advice.
Yes, using a reference to a pointer allows the function to change what
the pointer points to, which can be useful when the function allocates
memory, though I would have preferred to return a pointer instead.

Consider this:

#include <iostream>

void f(char* a)
{
a = "Hello World";
}

void g(char*& a)
{
a = "Hello World";
}

int main()
{
char* s = "Init";
f(s);
std::cout << s << "\n";
g(s);
std::cout << s << "\n";
}

Since f() did not take a reference to a pointer as argument it can not
change what s points to, but g() can.

--
Erik Wikström
Dec 24 '07 #3
ka************* ******@gmail.co m wrote:
Hi,

Recently i came across a functiion declaration as below

void f(char *&a);

Nowhere i have come across this style. I understand, passing by
reference is always better(to avoid copying), that too added with
const like

void f(const std::string &a); //since it was char *a, i assume it to
be a string
Be careful here. Passing by const reference (as in your example) is an
optimization when you are dealing with an object that allocates memory
or who's size is larger than sizeof( int ), but only if you don't end up
copying the object inside the function anyway. The function declaration
you came across, "reference to pointer to char" is not such a beast.
Removing the 'const' qualifier makes it completely different.

A non-const reference parameter is used create an "in/out" parameter. In
other words, you can use that parameter to pass data into the function,
and it can use the parameter to pass data back out to the calling code.

Generally, non-const reference parameters are used as an optimization
when the return value allocates memory or is larger than sizeof int (to
avoid the copy... compilers can often do this particular optimization on
their own though so it isn't that common,) or when a function needs to
return multiple chunks of data.

Let's say for example that you have a char* that contains a bunch fields
separated by tabs (assume that other whitespace characters could be
embedded in these fields,) and you want to break these fields up into a
bunch of strings... How do you write a function that extracts each
field, then returns both the string extracted and the position of the
next field?

Here are some ideas to solve that problem:

string idea1( const char* in ) {
string result;
while ( *in && *in != '\t' )
result.push_bac k( *in );
return result;
}

The above function extracts the field, but the calling function must
advance the input on its own, like this maybe:

vector<stringfi elds;
while ( *data ) {
fields.push_bac k( idea1( data ) );
data += fields.back().s ize() + 1;
}

However, if we make the parameter an in/out one, then we can do this:

string idea2( const char*& inOut ) {
string result;
while ( *inOut && *inOut != '\t' )
result.push_bac k( *inOut++ );
++inOut;
return result;
}

Now the caller need not take care of pointer advancement on its own:

vector<stringfi elds
while ( *data ) {
fields.push_bac k( idea2( data ) ); // data is modified by the call
}

Of course, in returning the string, note that the function has to build
the string, then create a temporary copy of it to pass to the caller.
Often the compiler can optimize the copy away (look up return value
optimization (RVO)). However, if profiling shows this to be a
bottleneck, we can use:

void idea3( const char*& inOut, string& result ) {
result = string();
while ( *inOut && *inOut != '\t' )
result.push_bac k( *inOut++ );
++inOut;
}

which would be used like so:

vector<stringfi elds;
while ( *data ) {
string str;
idea3( data, str );
fields.push_bac k( str );
}
Dec 24 '07 #4
ka************* ******@gmail.co m wrote in news:1f7ca27b-5c4a-4458-a105-
fc**********@a3 5g2000prf.googl egroups.com:
Hi,

Recently i came across a functiion declaration as below

void f(char *&a);

Nowhere i have come across this style. I understand, passing by
reference is always better(to avoid copying), that too added with
Not necessarily true. Probably true in the case of non-trivial types.
char* isn't one of them. This function may want to be able to modify the
pointer that it was passed.
const like

void f(const std::string &a); //since it was char *a, i assume it to
be a string
So now you've traded a ref-to-pointer with a potential construction of a
temporary string object, with the attendant dynamic memory allocation
(probably) and memory copy. And you've changed the semantics of the
function.
This i came across in the book "Secrets of C++ Masters". Though this
book is old, i just wanted to know what it speaks of. I do not know
whether this is still accepted or was a part of pre-standard c++. I
tried a toy program with a function like this. It did compile fine and
executed successfully. As per the book, this style prevents pointer
copy(address copy) - is that true? atleast in c++. Pls advice.
Implementation-dependant as to what potential savings it might have.
Dec 24 '07 #5

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

Similar topics

4
2143
by: Carsten Spieß | last post by:
Hello all, i have a problem with a template constructor I reduced my code to the following (compiled with gcc 2.7.2) to show my problem: // a base class class Base{}; // two derived classes
3
2362
by: Bruno van Dooren | last post by:
Hi All, i have some (3) different weird pointer problems that have me stumped. i suspect that the compiler behavior is correct because gcc shows the same results. ---------------------------------------------- //example 1: typedef int t_Array; int main(int argc, char* argv)
35
2906
by: tuko | last post by:
Hello kind people. Can someone explain please the following code? /* Create Storage Space For The Texture */ AUX_RGBImageRec *TextureImage; /* Line 1*/ /* Set The Pointer To NULL */ memset(TextureImage,0,sizeof(void *)*1); /* Line 2*/ According to my knowledge in the first line
16
2310
by: junky_fellow | last post by:
According to Section A6.6 Pointers and Integers (k & R) " A pointer to one type may be converted to a pointer to another type. The resulting pointer may cause addressing exceptions if the subject pointer does not refer to an object suitably aligned in storage. It is guaranteed that a pointer to an object may be converted to a pointer to an object whose type requires less or equally strict storage alignment and back again without change;...
204
13124
by: Alexei A. Frounze | last post by:
Hi all, I have a question regarding the gcc behavior (gcc version 3.3.4). On the following test program it emits a warning: #include <stdio.h> int aInt2 = {0,1,2,4,9,16}; int aInt3 = {0,1,2,4,9};
16
2517
by: aegis | last post by:
Given the following: int a = 10; int *p; void *p1; unsigned char *p2; p = &a;
23
7818
by: bluejack | last post by:
Ahoy... before I go off scouring particular platforms for specialized answers, I thought I would see if there is a portable C answer to this question: I want a function pointer that, when called, can be a genuine no-op. Consider: typedef int(*polymorphic_func)(int param);
69
5603
by: fieldfallow | last post by:
Hello all, Before stating my question, I should mention that I'm fairly new to C. Now, I attempted a small demo that prints out the values of C's numeric types, both uninitialised and after assigning them their maximum defined values. However, the output of printf() for the long double 'ld' and the pointer of type void 'v_p', after initialisation don't seem to be right. The compiler used was gcc (mingw) with '-Wall', '-std=c99' and
27
8979
by: Erik de Castro Lopo | last post by:
Hi all, The GNU C compiler allows a void pointer to be incremented and the behaviour is equivalent to incrementing a char pointer. Is this legal C99 or is this a GNU C extention? Thanks in advance. Erik
8
2237
by: Martin Jørgensen | last post by:
Hi, "C primer plus" p.382: Suppose we have this declaration: int (*pa); int ar1; int ar2; int **p2;
0
9666
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
9511
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
10408
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10139
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
9020
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...
0
6769
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
5417
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...
2
3700
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
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.