avatar
被reference搞晕了# Programming - 葵花宝典
d*n
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?
avatar
c*e
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

avatar
c*e
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

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