g***e 发帖数: 577 | 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);
|
q*****g 发帖数: 72 | 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){
|
g***e 发帖数: 577 | 3 yep, I found it explained as return optimization in a book.
【在 q*****g 的大作中提到】 : "c = func2(a)" used default contructor, not copy constructor! : : 1
|
d****r 发帖数: 1017 | 4 但是为什么都是返回一个A类,func1调用copy constructor,
而func2调用default constructor呢? |
i*c 发帖数: 1132 | 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){
|
g***e 发帖数: 577 | 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呢?
|
X****r 发帖数: 3557 | 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 |
g***e 发帖数: 577 | 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
|