2016-09-17 68 views
2

访问数组的正确方法我如何在下面的代码是为了知道的valgrind tool.But访问使用参考主阵列arrref请告诉我通过参考

内存泄漏我不能够编译下面

#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; 

} 

由于

+0

为什么不干脆用指针来代替参考? –

+0

使用'std :: vector'。 – GManNickG

+0

你喜欢与内存泄漏跳舞吗? –

回答

0

所需的语法是(&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 
+2

静态数组听起来像一个可怕的想法,可以解决短期问题并导致长期问题。 – Yakk

+0

'静态数组'然后有人想要多线程 - 猜猜是什么...... –

+0

@EdHeal可能是你想详细说明在一个多线程中静态存储持续时间的POD数组会发生什么,多线程程序? –

-1

首先,它是不是一个好主意访问本地一些函数的变量在一些其他函数中。 函数返回类型是int &,它表示您要返回对int变量的引用。 如果您要访问的阵列的本地阵列“一”,那么函数应该被改写为 -

#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; 

    } 
+0

我认为'std :: vector func()'更好。我认为(但不知道)'std :: vector &func()'可能是未定义的行为 –

+0

不,我只是试了一下。并没有给出未定义的行为。 –

+0

你不能只尝试一次,以确定它是未定义的行为。我认为这是因为你正在提供一些关于利益的东西。我99.999%肯定这是未定义的行为。 –