473,662 Members | 2,551 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Copy ctor and pass-by-value

Hi,
Please help me to understand compiler behavior
concerning the following code:

class X{
* *int k;
public:
* *X(){ k=1; }
* *X( X & model ){
* * * k = model.k;
* * * model.k++;
* *}
* *void get(){ cout << "k = " << k << endl; }
};
X fun( X par ){
* * * * cout << "Inside: "; par.get();
* * * * return par;
}

int main(){
* *X inst1;
* *cout << "Before: "; inst1.get();
* *fun( inst1 );
* *cout << "After: "; inst1.get();
// * X inst2 = fun( inst1 );
* *return 0;
}

The function "fun" uses pass-by-value. According to ISO, "a function can
change the values of its non-const parameters, but these changes cannot
affect the values of the arguments except where a parameter is of a
reference type". The copy constructor does not guarantee not to change
the "model" parameter, in fact it does change it. Surprisingly, gcc v.4.1.1
(Linux Mandriva) allows this code to compile (and work). Still surprisingly
(for me), uncomenting the line with second function call using
return-by-value causes compiler to throw:
error: no matching function for call to 'X::X(X)'
note: candidates are: X::X(X&)
I thought that changing the object that is about to be destroyed is not such
violation of Rules as changing passed-by-value parameter. I can't also
understand the error message: the second function call in the code seems
the same as the first, except for not ignoring the return value.

First I thought it is a bug in a compiler, but I've also tried it with
Borland Builder 6: it does not even warn in both cases.
(Of course, changing the copy constructor and adding "const" in parameter
list solves the problem.)

Thanks for your time,
Dariusz

--
|\ Dariusz Bismor
/ | \ Instytut Automatyki Politechniki ¦l±skiej
/ | \ mailto:Da****** ******@polsl.pl
_/__|___\ http://www.ia.polsl.gliwice.pl
~~~~~~~ \________|~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~

Nov 29 '06 #1
5 1677
Dariusz Bismor wrote:
Hi,
Please help me to understand compiler behavior
concerning the following code:

class X{
int k;
public:
X(){ k=1; }
X( X & model ){
k = model.k;
model.k++;
}
void get(){ cout << "k = " << k << endl; }
};
X fun( X par ){
cout << "Inside: "; par.get();
return par;
}

int main(){
X inst1;
cout << "Before: "; inst1.get();
fun( inst1 );
cout << "After: "; inst1.get();
// Â* X inst2 = fun( inst1 );
return 0;
}

The function "fun" uses pass-by-value. According to ISO, "a function can
change the values of its non-const parameters, but these changes cannot
affect the values of the arguments except where a parameter is of a
reference type". The copy constructor does not guarantee not to change
the "model" parameter, in fact it does change it.
Yes, the copy constructor does. The function fun however doesn't.
Surprisingly, gcc v.4.1.1 (Linux Mandriva) allows this code to compile
(and work). Still surprisingly (for me), uncomenting the line with second
function call using return-by-value causes compiler to throw:
error: no matching function for call to 'X::X(X)'
note: candidates are: X::X(X&)
Well, you try to change the return value from fun. That's not allowed in
C++.
I thought that changing the object that is about to be destroyed is not
such violation of Rules as changing passed-by-value parameter. I can't
also understand the error message: the second function call in the code
seems the same as the first, except for not ignoring the return value.
The message is all about the return value. What happens here is that in fun,
par is copied into a temporary object of type X. Then in your function
call, that temporary is copied into inst2. However, the copy construtor
wants a reference to non-const X, and C++ forbids binding non-const
references to temporaries.

Nov 29 '06 #2

But how come this is getting compiled (after un commenting) in VS2005?

You mean to say that in this case VS2005 compiler has not followed the
standards?

Dheeraj

Rolf Magnus wrote:
Dariusz Bismor wrote:
Hi,
Please help me to understand compiler behavior
concerning the following code:

class X{
int k;
public:
X(){ k=1; }
X( X & model ){
k = model.k;
model.k++;
}
void get(){ cout << "k = " << k << endl; }
};
X fun( X par ){
cout << "Inside: "; par.get();
return par;
}

int main(){
X inst1;
cout << "Before: "; inst1.get();
fun( inst1 );
cout << "After: "; inst1.get();
// X inst2 = fun( inst1 );
return 0;
}

The function "fun" uses pass-by-value. According to ISO, "a function can
change the values of its non-const parameters, but these changes cannot
affect the values of the arguments except where a parameter is of a
reference type". The copy constructor does not guarantee not to change
the "model" parameter, in fact it does change it.

Yes, the copy constructor does. The function fun however doesn't.
Surprisingly, gcc v.4.1.1 (Linux Mandriva) allows this code to compile
(and work). Still surprisingly (for me), uncomenting the line with second
function call using return-by-value causes compiler to throw:
error: no matching function for call to 'X::X(X)'
note: candidates are: X::X(X&)

Well, you try to change the return value from fun. That's not allowed in
C++.
I thought that changing the object that is about to be destroyed is not
such violation of Rules as changing passed-by-value parameter. I can't
also understand the error message: the second function call in the code
seems the same as the first, except for not ignoring the return value.

The message is all about the return value. What happens here is that in fun,
par is copied into a temporary object of type X. Then in your function
call, that temporary is copied into inst2. However, the copy construtor
wants a reference to non-const X, and C++ forbids binding non-const
references to temporaries.
Nov 29 '06 #3
Dheeraj wrote:
>
But how come this is getting compiled (after un commenting) in VS2005?

You mean to say that in this case VS2005 compiler has not followed the
standards?

Dheeraj
Nop, not in VS, but in Borland Builder 6. But still, I can't understand
why the first function call is allowed.

Dariusz

(...)
--
|\ Dariusz Bismor
/ | \ Instytut Automatyki Politechniki ¦l±skiej
/ | \ mailto:Da****** ******@polsl.pl
_/__|___\ http://www.ia.polsl.gliwice.pl
~~~~~~~ \________|~~~~~ ~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~ ~~~~~

Nov 29 '06 #4
Dheeraj wrote:
>
But how come this is getting compiled (after un commenting) in VS2005?

You mean to say that in this case VS2005 compiler has not followed the
standards?
Yes. However, there might be some command line options to switch that
compiler into a more standard compliant mode.

Nov 29 '06 #5
Dheeraj wrote:
>
But how come this is getting compiled (after un commenting) in VS2005?
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or the group FAQ list:
<http://www.parashift.c om/c++-faq-lite/how-to-post.html>
Nov 29 '06 #6

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

Similar topics

3
4461
by: mescaline | last post by:
//Consider the simple program with inheritance, plain init for A, copy ctr for B #include <iostream> using namespace std; class Base{ public: Base(){cout << "Base, default" << endl;} Base(const Base &){cout << "Base, Copy Ctor" << endl;} };
7
2679
by: skishorev | last post by:
Hi, I know What is the copy constructor. I don't know where and why we have to use copy constructor. If You know please give to me with a situation where we have to use or with a small example. I am waiting for your reply. Thanks & Regards, Sai Kishore
5
1692
by: nagrik | last post by:
Hello group, Last week I picked up a thread, which pointed out that if a copy constructor is created with pointers instead of reference, there is a danger of it going in infinite recursion. My observation: 1. Compiler does not complain.
3
3390
by: John Salmon | last post by:
g++ complains about illegal access to a private member when the following is compiled with a private copy constructor for the class C. When the copy constructor is public, the program runs and demonstrates(?) that the copy constructor is never called (at least no sign of its chatter on std::cout is visible). So - is it necessary to have a public copy constructor in order to use "function style" initializers for an array of objects? ...
10
4015
by: campos | last post by:
"Effective C++ 3rd Edition" Item 6, P39 ------------------------------------------------------- class Uncopyable { protected: // allow construction Uncopyable() {} // and destruction of ~Uncopyable() {} // derived objects... private: Uncopyable(const Uncopyable&); // ...but prevent copying
13
2462
by: Jeroen | last post by:
Hi all, I'm trying to implement a certain class but I have problems regarding the copy ctor. I'll try to explain this as good as possible and show what I tried thusfar. Because it's not about a certain code syntax but more a 'code architecture' thing , I'll use simple example classes (which are certainly not complete or working...) just to illustrate the idea (and I may make some mistakes because I'm not that experienced...). The...
6
1568
by: Richard Thompson | last post by:
Hi - I have a program which was previously working (but wasn't well tested). I've added a new function call, and it now doesn't compile. The call requires a copy constructor, but the compiler appears to think that it actually calls one of the *other* constructors. The copy ctor would work in this context, but the other ctor can't be used (it leads to a template instantiation error, which the compiler is reporting).
3
2047
by: subramanian100in | last post by:
If we provide any ctor for a class the compiler does not supply the default ctor. However if we do not provide the copy ctor but provide any other ctor, the compiler still supplies the copy ctor. Why doesn't the compiler supply the default ctor but still supplies the copy ctor when we have defined any other ctor ? Kindly explain
2
2161
by: subramanian100in | last post by:
If we do not provide any ctor for a class, the compiler provides the default ctor and copy ctor if needed. Consider a class Test. Suppose we provide some ctor in class Test but do not provide the default ctor. Suppose we try to create Test obj;
15
1818
by: subramanian100in | last post by:
consider the following program: #include <iostream> using namespace std; class Test { public: Test(int xx) : x(xx) { cout << x << endl; }
0
8432
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
8344
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
8857
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
8764
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
8633
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
7367
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
6186
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
4180
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
1752
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.