【问题标题】:Whats the correct way of accessing the array through reference通过引用访问数组的正确方法是什么
【发布时间】:2016-09-17 14:02:09
【问题描述】:

如何使用引用 arrref 访问 main 中的数组

下面代码中的内存泄漏是为了了解valgrind工具。但是我无法编译下面的代码

#include <iostream>
int& func();
int main() 
{

    int &arrref = func();
    std::cout<<arrref[1];//Error
    std::cout<<&arrref[1];//Error
}

int& func()
{

    int *a = new int[10];
    for(int i = 0;i<10 ;++i)
            a[i] = i*2;
    return *a;

}

谢谢

【问题讨论】:

  • 为什么不简单地使用指针而不是引用?
  • 使用std::vector
  • 你喜欢与内存泄漏共舞吗?

标签: c++


【解决方案1】:

所需的语法是(&amp;arrref)[1]。这指的是数组的第二个元素。

但请确保从func 返回的引用确实引用了具有足够数量元素的数组的第一个元素。

为了清楚地传达func 返回对数组的引用,您可能希望返回一个范围,例如:

#include <iostream>
#include <boost/range/as_array.hpp>

boost::iterator_range<int*> func() {
    static int array[2] = {1, 2};
    return boost::as_array(array);
}

int main() {
    auto array = func();
    std::cout << array[0] << '\n';
    std::cout << array[1] << '\n';
    for(auto const& value: func())
        std::cout << value << '\n';
}

输出:

1
2
1
2

【讨论】:

  • 静态数组听起来像是一个可怕的想法,它会解决短期问题并导致长期问题。
  • @EdHeal 您是否想详细说明在多线程程序中具有静态存储持续时间的 POD 数组会发生什么?
  • 两个线程同时访问和使用相同的数据。会得到很奇怪的结果
  • @Yakk 并导致长期问题。 - 可能会,也可能不会,正确答案 - 视情况而定。
  • @EdHeal 抱歉打断你,但多个线程访问同一个对象不会导致任何问题,只要不存在竞争条件。
【解决方案2】:

首先,在其他一些函数中访问一个函数的局部变量并不是一个好主意。 函数返回类型是 int& ,表示您要返回对 int 变量的引用。 如果要访问数组本地数组'a',则该函数应重写为-

 #include <iostream>
 int* func();

  int main() 
  {

  int *arrref = func();
   std::cout<<arrref[1];//Error
  std::cout<<&arrref[1];//Error


  }

  int *func()
 {

     int *a = new int[10];
     for(int i = 0;i<10 ;++i)
        a[i] = i*2;
     return a;

  }

或者你也可以使用向量 -

  #include<iostream>
  #include<vector>
  std::vector<int>& func();

  int main() 
  {

    std::vector<int>& arrref = func();
    std::cout<<arrref[1];//Error
    std::cout<<&arrref[1];//Error


   }

   std::vector<int>& func()
   {

    std::vector<int> a(10);
    for(int i = 0;i<10 ;++i)
        a[i] = i*2;
    return a;

    }

【讨论】:

  • 我认为std::vector&lt;int&gt; func() 更好。我认为(但不确定)std::vector&lt;int&gt;&amp; func() 可能是未定义的行为
  • 不,我刚试过。并且没有给出未定义的行为。
  • 您不能只尝试一次就确定它是未定义的行为。我认为这是因为您正在参考风险中的某些东西。我 99.999% 确信这是未定义的行为。
  • 在我的回答中,我已经提到在其他函数中访问一个函数的局部变量不是一个好主意。所以肯定上述方法是无效的。我只是在告诉一种有效的方法来做同样的事情。我同意它可能会显示未定义的行为,但它也回答了上述问题。
猜你喜欢
  • 1970-01-01
  • 2014-08-16
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多