d*******n 发帖数: 369 | 1 以下2种case,哪些对?
// use template for generality
case 1
T fn(T & in)
{
T &value = in; //two references point to one object (ok?)
// do something
return value; //is a reference returned?
}
case 2
T &fn(T & in)
{
T &value = in;
// do something
return value; //is a reference returned? what difference from the case 1?
}
My purpose: if class T is big, it's efficient to pass/return its reference.
The above 2 cases will do? | c********e 发帖数: 383 | 2 IMHO, both case 1 and 2 are correct c++ code.
for case 1 when the reference is returned, it is made into
a temporary object first, which is the semantic of return by value.
for all POD and user defined types, there must be a copy constructor
which takes a reference type and return (not really return, but contruction)
a object of that type. which is then returned to the caller.
so ur case 1 fn semantic is: (assuming do something instead of do nothing
in your fn definition)
change the object passe
【在 d*******n 的大作中提到】 : 以下2种case,哪些对? : // use template for generality : case 1 : T fn(T & in) : { : T &value = in; //two references point to one object (ok?) : // do something : return value; //is a reference returned? : } : case 2
| c********e 发帖数: 383 | 3 IMHO, both case 1 and 2 are correct c++ code.
for case 1 when the reference is returned, it is made into
a temporary object first, which is the semantic of return by value.
for all POD and user defined types, there must be a copy constructor
which takes a reference type and return (not really return, but contruction)
a object of that type. which is then returned to the caller.
so ur case 1 fn semantic is: (assuming do something instead of do nothing
in your fn definition)
change the object passe
【在 d*******n 的大作中提到】 : 以下2种case,哪些对? : // use template for generality : case 1 : T fn(T & in) : { : T &value = in; //two references point to one object (ok?) : // do something : return value; //is a reference returned? : } : case 2
|
|