avatar
C++问题,confusing...# Programming - 葵花宝典
g*e
1
#include
using namespace std;
class A{
int i; // a mark to show the difference
public:
A(int ii=1):i(ii){} // default constructor
A(const A& a) {i=a.i+1;} // copy constructor,just increase i by 1
int ivalue() const {return i;} //the function to show the mark
};
A func1(const A& a){
return a;
}
A func2(const A& a){
A b(a.ivalue());
return b;
}
int main(){
A a;
A b=func1(a);
A c=func2(a);
avatar
q*g
2
"c = func2(a)" used default contructor, not copy constructor!

1

【在 g***e 的大作中提到】
: #include
: using namespace std;
: class A{
: int i; // a mark to show the difference
: public:
: A(int ii=1):i(ii){} // default constructor
: A(const A& a) {i=a.i+1;} // copy constructor,just increase i by 1
: int ivalue() const {return i;} //the function to show the mark
: };
: A func1(const A& a){

avatar
g*e
3
yep, I found it explained as return optimization in a book.

【在 q*****g 的大作中提到】
: "c = func2(a)" used default contructor, not copy constructor!
:
: 1

avatar
d*r
4
但是为什么都是返回一个A类,func1调用copy constructor,
而func2调用default constructor呢?
avatar
i*c
5
你用的是gcc吧。 用VC的结果是122。

1

【在 g***e 的大作中提到】
: #include
: using namespace std;
: class A{
: int i; // a mark to show the difference
: public:
: A(int ii=1):i(ii){} // default constructor
: A(const A& a) {i=a.i+1;} // copy constructor,just increase i by 1
: int ivalue() const {return i;} //the function to show the mark
: };
: A func1(const A& a){

avatar
g*e
6
I guess the compiler didnt construct a local object, then return it in func2.
It constructs the final destination directly in the function.

【在 d****r 的大作中提到】
: 但是为什么都是返回一个A类,func1调用copy constructor,
: 而func2调用default constructor呢?

avatar
X*r
7
Copied from the holy standard:
12.8 Copying class objects [class.copy]
15Whenever a class object is copied and the original object and the copy
have the same type, if the implementation can prove that either the
original object or the copy will never again be used except as the
result of an implicit destructor call (_class.dtor_), an implementa-
tion is permitted to treat the original and the copy as two different
ways of referring to the sam
avatar
g*e
8
强就一个字.

【在 X****r 的大作中提到】
: Copied from the holy standard:
: 12.8 Copying class objects [class.copy]
: 15Whenever a class object is copied and the original object and the copy
: have the same type, if the implementation can prove that either the
: original object or the copy will never again be used except as the
: result of an implicit destructor call (_class.dtor_), an implementa-
: tion is permitted to treat the original and the copy as two different
: ways of referring to the sam

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。