1

我有这种情况,如果通过 const 参考剂量继电器返回保存一些东西,我会徘徊,这个函数可能会被调用数百次。

我有:
返回 int 作为 const 引用的通用容器

struct Val
{
 public:
    Val(int& v)
    {
        iVal = v;
    }

    const int& toInt()
    {
        return iVal;
    }

private:
    int iVal;
};

获取数字的函数:

Val Mo::doSomthing()
{
  Val v(444444);
  return v;
}

调用 d oSomthing().toInt()

int x = 0;
class Foo {
...
....
Mo mo;
void Foo::setInt(float scaleX)
{

   x = mo.doSomthing().toInt();
   //x is class member which other functions are using it 

}
...
...
..
}

在这种情况下,是否有任何理由使用 const 引用来节省一些位?

4

1 回答 1

2

一般来说,对于标量类型,按值返回它们更便宜。引用(和指针)的大小(字长)与通常的标量类型几乎相同。如果您返回一个 int& 您将返回相同数量的数据,但是当您访问引用的数据时,运行平台必须解析引用(访问引用的内存)。

但前面的评论是对的:先测量它。这是一种微优化。

于 2017-01-01T10:24:21.157 回答