473,703 Members | 3,125 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

argument passing by value and temporaries

Hi, I have just started learning C++ language..
I've read much even tried to understand the way standard says but still
can't get the grasp of that concept.

When parameters are passed/returned by value temporaries are
created?(I'm not touching yet the cases where standard allows
optimizations from the side of implementations to avoid copying)
If so, please quote part of the standard that says that.
Assuming it is true, I can imagine two cases such as:

struct X {
};

void foo(X b);

....

int main(int argc, char* argv[]) {
X a;
foo(a); // first case
foo(X()); // second one
}

In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
So copy .ctor is used two times here ?

In the second case X() expression that is rvalue of type X.. I'm not
sure as well about the terminology to use here... X() expression is not
temporary object right? it is just a rvalue(that is value initialized)
and temporary object of type X is *copy* constructed with that rvalue
and then 'b' object is also copy constructed from that temporary...

Same holds true for returning objects ?

Now, if everything holds true, implementators can avoid two phase
copying, like in first example instead to copy construct temporary with
'a' object and then to copy construct 'b' object with that temporary,
'b' object is directly copy constructed with the 'a' object?

And in second case X() doesn't create temporary but directly copy
constructs 'b' ?

TIA.

--
David

Dec 14 '06 #1
12 2585

da*****@mail.ru wrote:
Hi, I have just started learning C++ language..
I've read much even tried to understand the way standard says but still
can't get the grasp of that concept.

When parameters are passed/returned by value temporaries are
created?(I'm not touching yet the cases where standard allows
optimizations from the side of implementations to avoid copying)
If so, please quote part of the standard that says that.
Assuming it is true, I can imagine two cases such as:

struct X {
};

void foo(X b);

...

int main(int argc, char* argv[]) {
X a;
foo(a); // first case
foo(X()); // second one
}

In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
I don't believe the C++ standard requires creating a temporary variable
and then using it to initialize the function parameter with the copy
constructor. It should require only initializing the function
parameter with the copy constructor being passed the function argument.
Where did you get the idea that a temporary is created? Can you quote
a verse in the standard?

As for actual implementation, as opposed to the standard, when you run
said code only one default constructor for your initial declarion of
'a', and one copy constructor call when you pass the argument is
actually made in gcc.

--
Ivan
http://www.0x4849.net

Dec 14 '06 #2

Ivan Novick wrote:
da*****@mail.ru wrote:
Hi, I have just started learning C++ language..
I've read much even tried to understand the way standard says but still
can't get the grasp of that concept.

When parameters are passed/returned by value temporaries are
created?(I'm not touching yet the cases where standard allows
optimizations from the side of implementations to avoid copying)
If so, please quote part of the standard that says that.
Assuming it is true, I can imagine two cases such as:

struct X {
};

void foo(X b);

...

int main(int argc, char* argv[]) {
X a;
foo(a); // first case
foo(X()); // second one
}

In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
I don't believe the C++ standard requires creating a temporary variable
and then using it to initialize the function parameter with the copy
constructor. It should require only initializing the function
parameter with the copy constructor being passed the function argument.
Where did you get the idea that a temporary is created? Can you quote
a verse in the standard?

As for actual implementation, as opposed to the standard, when you run
said code only one default constructor for your initial declarion of
'a', and one copy constructor call when you pass the argument is
actually made in gcc.

--
Ivan
http://www.0x4849.net
When I was searching NG for this type of question that IMHO has been
asked many times, I saw in few of the posts that said temporaries are
created when passing/returning arguments by value.. I can't find these
posts right now, but does it matter anyways? I didn't say I read it
from standard, I just asked if it was really defined in standard that
way... Sorry for being unclear in my first post if it was understood
like that..

And can you provide a verse in the standard where it doesn't require so
? Or any other statement that implies that temporaries are not made
during argument passing/returing by value. I'm really confused about
that matter and I'm in need of clear explaination of standard maybe
with examples too...

Thank you in advance.

--
David

Dec 14 '06 #3

"Ivan Novick" <iv**@0x4849.ne twrote in message
news:11******** **************@ t46g2000cwa.goo glegroups.com.. .
>
da*****@mail.ru wrote:
>Hi, I have just started learning C++ language..
I've read much even tried to understand the way standard says but still
can't get the grasp of that concept.

When parameters are passed/returned by value temporaries are
created?(I'm not touching yet the cases where standard allows
optimization s from the side of implementations to avoid copying)
If so, please quote part of the standard that says that.
Assuming it is true, I can imagine two cases such as:

struct X {
};

void foo(X b);

...

int main(int argc, char* argv[]) {
X a;
foo(a); // first case
foo(X()); // second one
}

In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
I don't believe the C++ standard requires creating a temporary variable
and then using it to initialize the function parameter with the copy
constructor. It should require only initializing the function
parameter with the copy constructor being passed the function argument.
Where did you get the idea that a temporary is created? Can you quote
a verse in the standard?
Well, it does create a temporary object, but that object is the parameter
itself. It doesn't create a temporary and then create the parameter from
that.
As for actual implementation, as opposed to the standard, when you run
said code only one default constructor for your initial declarion of
'a', and one copy constructor call when you pass the argument is
actually made in gcc.
yep.

-Howrad
Dec 14 '06 #4
Howard wrote:
"Ivan Novick" <iv**@0x4849.ne twrote in message
news:11******** **************@ t46g2000cwa.goo glegroups.com.. .

da*****@mail.ru wrote:
Hi, I have just started learning C++ language..
I've read much even tried to understand the way standard says but still
can't get the grasp of that concept.

When parameters are passed/returned by value temporaries are
created?(I'm not touching yet the cases where standard allows
optimizations from the side of implementations to avoid copying)
If so, please quote part of the standard that says that.
Assuming it is true, I can imagine two cases such as:

struct X {
};

void foo(X b);

...

int main(int argc, char* argv[]) {
X a;
foo(a); // first case
foo(X()); // second one
}

In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
I don't believe the C++ standard requires creating a temporary variable
and then using it to initialize the function parameter with the copy
constructor. It should require only initializing the function
parameter with the copy constructor being passed the function argument.
Where did you get the idea that a temporary is created? Can you quote
a verse in the standard?

Well, it does create a temporary object, but that object is the parameter
itself. It doesn't create a temporary and then create the parameter from
that.
As for actual implementation, as opposed to the standard, when you run
said code only one default constructor for your initial declarion of
'a', and one copy constructor call when you pass the argument is
actually made in gcc.

yep.

-Howrad
Howard,

Can you clarify what do you mean when you say "Well, it does create a
temporary object, but that object is the parameter itself" Are you
saying that parameters are temporary objects that doubles up my
confusion ?

At any rate can anybody provide clear definition, maybe quotation(s)
from standard that answers my questions?

TIA.

--
David

Dec 14 '06 #5
>In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is
itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
I don't believe the C++ standard requires creating a temporary variable
and then using it to initialize the function parameter with the copy
constructor. It should require only initializing the function
parameter with the copy constructor being passed the function argument.
Where did you get the idea that a temporary is created? Can you quote
a verse in the standard?

Well, it does create a temporary object, but that object is the parameter
itself. It doesn't create a temporary and then create the parameter from
that.
As for actual implementation, as opposed to the standard, when you run
said code only one default constructor for your initial declarion of
'a', and one copy constructor call when you pass the argument is
actually made in gcc.

yep.

-Howrad

Howard,

Can you clarify what do you mean when you say "Well, it does create a
temporary object, but that object is the parameter itself" Are you
saying that parameters are temporary objects that doubles up my
confusion ?
When passing an object by value, the object specified in the function call
(i.e., being "passed") is actually copied into a temporary object which is
created in automatic memory (or "on the stack", if you prefer). Inside the
called function, any reference to the parameter (i.e, any use of its name in
the source code) refers to that temporary object. So any changes to the
parameter object inside that function actually changes the temporary object
that was created. After the function returns, the temporary is destroyed
and those changes are lost.

If the object is passed by reference, however, then any use of the parameter
inside the function is actually affecting the object that was specified when
calling the function, not a temporary copy made from it.

-Howard


Dec 14 '06 #6

Howard wrote:
In the first case temporary variable is created that is *copy*
constructed with 'a' object and upon function call 'b' object is
itself
copy constructed with that temporary variable.. am I doing right
assumtions iff (When parameters are passed/returned by value
temporaries are created) ?
I don't believe the C++ standard requires creating a temporary variable
and then using it to initialize the function parameter with the copy
constructor. It should require only initializing the function
parameter with the copy constructor being passed the function argument.
Where did you get the idea that a temporary is created? Can you quote
a verse in the standard?


Well, it does create a temporary object, but that object is the parameter
itself. It doesn't create a temporary and then create the parameter from
that.

As for actual implementation, as opposed to the standard, when you run
said code only one default constructor for your initial declarion of
'a', and one copy constructor call when you pass the argument is
actually made in gcc.


yep.

-Howrad
Howard,

Can you clarify what do you mean when you say "Well, it does create a
temporary object, but that object is the parameter itself" Are you
saying that parameters are temporary objects that doubles up my
confusion ?

When passing an object by value, the object specified in the function call
(i.e., being "passed") is actually copied into a temporary object which is
created in automatic memory (or "on the stack", if you prefer). Inside the
called function, any reference to the parameter (i.e, any use of its name in
the source code) refers to that temporary object. So any changes to the
parameter object inside that function actually changes the temporary object
that was created. After the function returns, the temporary is destroyed
and those changes are lost.

If the object is passed by reference, however, then any use of the parameter
inside the function is actually affecting the object that was specified when
calling the function, not a temporary copy made from it.

-Howard
So, what happens in second example?
foo(X()); based on what you said b is directly copy constructed by X()
? Does it hold true when returning by value and when throwing an
exception? for example

X foo() {
X c;
return c;
}

....
X a = foo(); // Is a directly copy constructed by c ? and if so then
what's difference between optimized implementation and not optimized
one if argument passing/returning by value directly copy constructs
objects...

Now as far as exceptions are concerned, as I've read throw T() causes
always temporary object to be created and copy constructed by T() and
in catch clause(s) it is caught by reference or object is copy
constructed by that temporary depending how catch clause is
written(T&,T).. why it is any different from parameter passing by value
or returning by value ? and what kind of a optimization can
implementation offer ? I'm still in state of confusion, and would
appreciate if anybody could shed some light in my understanding of
these concepts.

TIA.

--
David

Dec 14 '06 #7
Howard wrote:
Can you clarify what do you mean when you say "Well, it does create a
temporary object, but that object is the parameter itself" Are you
saying that parameters are temporary objects that doubles up my
confusion ?

When passing an object by value, the object specified in the function call
(i.e., being "passed") is actually copied into a temporary object which is
created in automatic memory (or "on the stack", if you prefer).
Howard, I think you are using a looser definition of 'temporary' than
either Ivan or the Standard (if - as it seems - you are applying it to
automatic variables in general). Section 12.2 covers the creation of
temporary objects, and function parameters aren't in the list.

Ivan, even in your second case you only have 1 copy constructor at
most:
1) Default construct your temporary X.
2) Copy construct your function parameter from the temporary.
As you mentioned the compiler is allowed to default construct the X
directly in-place. If you have g++, play around with the
-fno-elide-constructors switch.

I think the confusion arose because you thought that X() doesn't
construct a temporary variable - it does. From Section 5.2.3:
"... the expression T(x1, x2, ...) is equivalent in effect to the
declaration T t(x1, x2, ...); for
some invented temporary variable t, with the result being the value of
t as an rvalue."

Dec 14 '06 #8
da*****@mail.ru wrote:
>
X foo() {
X c;
return c;
}

...
X a = foo();
Here:
1) c is default constructed
2) the temporarary for the return value is copy-constructed from c
3) a is copy constructed from the temporary.

But the optimisations mean that either or both of the copy
constructions can be eliminated. I expect that you modified your
example from section 12.8.15 of the standard, but in case you didn't:
read that section, it is helpful.
Now as far as exceptions are concerned, as I've read throw T() causes
always temporary object to be created and copy constructed by T()
This *can* happen, but as above, the copy construction may be optimised
away.
in catch clause(s) it is caught by reference or object is copy
constructed by that temporary depending how catch clause is
written(T&,T).. why it is any different from parameter passing by value
or returning by value ?
It isn't any different, except that the temporary is (or would be)
created without the cv qualifiers - this means that you can throw an
rvalue and catch a non-const reference. You wouldn't be able to do this
in normal parameter passing. Other than that, it's like calling a
funcion.
and what kind of a optimization can
implementation offer ?
>From section 12.5 again:
"- in a return statement in a function with a class return type, when
the expression is the name of a non-volatile automatic object with the
same cv-unqualified type as the function return type, the copy
operation can be omitted by constructing the automatic object directly
into the function's return value
- when a temporary class object that has not been bound to a reference
(12.2) would be copied to a class object with the same cv-unqualified
type, the copy operation can be omitted by constructing the temporary
object directly into the target of the omitted copy"

Dec 15 '06 #9

Pete C wrote:
Ivan, even in your second case you only have 1 copy constructor at
most:
Sorry Ivan - I meant to reply to dave, not you!

Dec 15 '06 #10

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

Similar topics

3
1775
by: Frank Bechmann | last post by:
Eventually most of you will not learn much from this because it's just another event in the 'default argument value gotcha' series, but because it cost me some hours yesterday to spot this 'error' in a famous python tool I thought it might still help other people to save some time. I tried to use some method which was documented to write to 'sys.stdout' per default so that changing 'sys.stdout' to bind to another object should allow to...
8
3964
by: Alex Vinokur | last post by:
Various forms of argument passing ================================= C/C++ Performance Tests ======================= Using C/C++ Program Perfometer http://sourceforge.net/projects/cpp-perfometer http://alexvn.freeservers.com/s1/perfometer.html
6
3676
by: Jason Heyes | last post by:
I am interested in the lifetime of a function argument in two cases. They are: 1. void foo(Bar bar); 2. void foo(const Bar &bar); In each case I call foo like so: foo(Bar());
4
3545
by: Rein Anders Apeland | last post by:
Consider the following working code: #include <memory> #include <iostream> void print_ptr( const std::auto_ptr< int > & thePtr = std::auto_ptr< int >() ) {
1
1969
by: User1014 | last post by:
Since you can pass a function to a ... erm...... function.... how to you use the result of a function as the argument for another function instead of passing the actual function to it. i.e. function foo2(){} function foo(func){}
3
3404
by: matko | last post by:
This is a long one, so I'll summarize: 1. What are your opinions on raising an exception within the constructor of a (custom) exception? 2. How do -you- validate arguments in your own exception constructors? I've noticed that, f.ex., ArgumentException accepts null arguments without raising ArgumentNullException. Obviously, if nothing is to be supplied to the exception constructor, the default constructor should
17
1679
by: Summercool | last post by:
I wonder which language allows you to change an argument's value? like: foo(&a) { a = 3 } n = 1 print n
17
2089
by: Klaas Vantournhout | last post by:
Hi all, I was wondering if it is possible if you can check in a function if one of the arguments is temporary. What I mean is the following. A is a class, foo is a function returning a class and bar is a function using A is an argument returning something else class A;
8
4424
by: Ruben | last post by:
error: passing `const Weight' as `this' argument of `float Weight::wgt()' discards qualifiers seems to be some sort of standard error format that I'm not understanding. I have code that looks like this header file
0
9244
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...
0
8961
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
7853
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
6585
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
5922
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
4421
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...
1
3114
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
2439
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2058
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.