通过值和参考,对象构建返回对象之间的区别
The difference between returning an object by value and by reference,object construction
该函数的返回类型真正意味着什么?当我们返回对象时会发生什么?逐价和逐回报之间有什么区别?
class A{
...
};
A f1(){
A *temp = new A;
return *temp;
}
const A& f2(){
A *temp = new A;
return *temp;
}
int main(){
A object1 = f1();
A object2 = f2();
return 0;
}
我使用台阶调试(F10)在VS2010上尝试了此示例代码。令人惊讶的是,复制构造函数仅被称为2次。一次,从F1函数,一次从主函数。为什么复制构造函数是从F1调用的?如何构造对象1?我知道这是一个非常糟糕的代码,泄漏了资源,但是我试图将注意力集中在问题上。
您不能"返回参考"。这句话是一种口语,如果您实际关心细节,则掩盖了细节。
函数调用表达式(例如f(a, b, c)
)是一个表达式,当评估时会产生A value 。值绝不是参考。除了它的类型外,所有关于值的重要内容都是它的 value类别,即是lvalue,xvalue还是prvalue。
C 中有一种常见的方式来编码类型系统中的值类别,该类型用于函数返回类型,铸件和decltype
。它是这样的。假设U
是对象类型。
- 使用
U f()
,f()
是一个prvalue,decltype(f())
是U
- 使用
U& f()
,f()
是一个lvalue,decltype(f())
是U&
- 使用
U&& f()
,f()
是XValue,decltype(f())
是U&&
这里重要的是 f
始终"返回 U
",但是重要的是 value返回。
此外,给定U
类型的glvalue x
-
static_cast<U>(x)
是一个prvalue("副本"或"加载"), -
static_cast<U&>(x)
是一个LVALUE, -
static_cast<U&&>(x)
是xvalue(这是std::move
所做的)。
因此,总而言之,以下两个陈述是正确的:
- "
f
的返回类型是U&
。" - "函数
f
返回lvalue。"
俗话说,人们会谈论"返回参考",但他们真正的意思是"返回glvalue"(因为两种参考返回类型用于两种glvalue)。Glvalue和Prvalue之间的区别是我们通常最关心的区别,因为Glvalue是现有位置,而Prvalue是Guarnanteed-Inique New副本。
您的意思是呼叫和呼叫val ??
,逐价之间有什么区别 和返回参考?
我将在以下示例中为您解释:
#include "iostream"
int calc1() { // call by value
int c = 1 + 1;
return c; // In this case you need to return the value
}
void calc2(int *c) { // Call by ref (with pointer)
*c = 1 + 1;
} // In this case, you are working with pointers, thus you don't need to return the value
int main() {
int c;
// call by value
c = calc1();
printf("%in",c);
c = 0;
// call by ref
calc2(&c); // you need to pass the address of the variable
printf("%in",c);
return 0;
}
该函数的返回类型的意思是什么?
#include "iostream"
int calc1() { // return type is integer
int i = 1 + 1;
return i; // In this case you return an integer
}
double calc2 (){ // return type is double
double c = 1.5 + 1.5;
return c; // In this case you return an double
}
int main() {
int i;
double d;
// call by value
i = calc1(); // here you will get an integer back
printf("%in",i);
d = calc2(); // Here you will get an double back
printf("%fn",d);
return 0;
}
您需要为函数指定返回类型,例如变量的类型。您将需要此,以指定返回值的类型。在上面的示例中,我将calc2()
的返回值分配给double d
为双重。如果将calc1()
的返回值分配给double d
,则会从编译器中获得错误。
- 如何为 mlpack 的 kmeans 构建 HamerlyKmeans 对象
- 如何在构建对象堆栈时解决转换错误?
- 生成文件不构建对象,我告诉它如何
- 使用C对象指针构建PyObject*
- 从单个.cpp构建共享对象
- 仅在函数内部构建对象时EXC_BAD_ACCESS
- lambda 对象构建成本高吗?
- 如何构建程序以避免查询对象类型?
- 尝试与从 CUDA 对象构建的共享库链接时未定义的符号
- 是否有任何可能的方法将事件(自定义)附加到在运行时创建的对象?[C 构建器]
- C 如何停止对象构建失败的执行
- 通过值和参考,对象构建返回对象之间的区别
- 如何将项目共享"system calls"作为单例对象构建和链接到引导加载程序?
- 使用操作员= C 对象构建
- cmake,我可以从可执行对象构建一个库吗?
- 为什么由指针和对象构建的局部变量显示不同的输出
- 如何为我在C++中创建的对象构建迭代器
- 在OpenCV中从Mat对象构建图像
- 延迟C++静态对象构建-Linux上的GCC
- 当从固定结构体中存储的对象构建函数时,c++ lambda构建静态函数返回意外值