通过值和参考,对象构建返回对象之间的区别



该函数的返回类型真正意味着什么?当我们返回对象时会发生什么?逐价和逐回报之间有什么区别?

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,则会从编译器中获得错误。

最新更新