【问题标题】:What happens when passing reference to literal in C++?在 C++ 中传递对文字的引用时会发生什么?
【发布时间】:2009-03-19 07:00:22
【问题描述】:

这里发生了什么:

double foo( const double& x ) {
   // do stuff with x
}

foo( 5.0 );
  1. 编译器是否创建匿名变量并将其值设置为 5.0?
  2. x 是否引用了只读内存中的内存位置?这是一个奇怪的措辞,我知道...

编辑:我忘记了 const 关键字...

【问题讨论】:

    标签: c++


    【解决方案1】:

    为此目的创建了一个临时变量,它通常在堆栈上创建。

    您可以尝试 const_cast,但无论如何它都没有 pontless,因为一旦函数返回,您将无法再访问变量。

    【讨论】:

    • 这对我来说似乎效率很低。使用声明的值在只读段中创建一个内存位置并使用它而不是在堆栈上创建一个变量不是更好吗?当然,所有幕后...
    • 无论如何,这取决于实现。而 double 并没有那么大。
    • 临时变量创建也适用于对象。如果它是一个 Class 而不是 double ,那么会创建一个临时对象,并且也会调用它的构造函数。
    • 这个问题是针对原语的。在堆栈上创建一个变量似乎有点浪费,不仅仅是内存(在递归的情况下,也许?!?!),但运行时也是如此。我想实现依赖就是所有......
    • 不一定是这样的浪费。如果您传递在静态存储中分配的值,则访问它的代码将不得不读取它,这可以减少缓存局部性。
    【解决方案2】:
    1. 编译器可能会创建 const 字面量,但这不是变量。
    2. 非常量引用不能指向文字。

      $ g++ test.cpp test.cpp:在函数int main()': test.cpp:10: error: invalid initialization of non-const reference of type 'double&' from a temporary of type 'double' test.cpp:5: error: in passing argument 1 ofdouble foo(double&)'

    test.cpp:

    #include <iostream>
    
    using namespace std;
    
    double foo(double & x) {
        x = 1;
    }
    
    int main () {
        foo(5.0);
    
        cout << "hello, world" << endl;
        return 0;
    }
    

    另一方面,您可以将文字传递给 const 引用,如下所示。 test2.cpp:

    #include <iostream>
    
    using namespace std;
    
    double foo(const double & x) {
        cout << x << endl;
    }
    
    int main () {
        foo(5.0);
    
        cout << "hello, world" << endl;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2017-06-20
      • 2012-03-18
      • 2011-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多