C++ functions returning arrays

后端 未结 3 1867
梦谈多话
梦谈多话 2021-01-14 23:55

I am sort of new to C++. I am used to programming in Java. This particular problem is causing me great issues, because C++ is not acting like Java when it is dealing with Ar

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 00:25

    Because your array is stack allocated. Moving from Java to C++, you have to be very careful about the lifetime of objects. In Java, everything is heap allocated and is garbage collected when no references to it remain.

    Here however, you define a stack allocated array a, which is destroyed when you exit the function getArray. This is one of the (many) reasons vectors are preferred to plain arrays - they handle allocation and deallocation for you.

    #include 
    
    std::vector getArray() 
    {
        std::vector a = {1, 2, 3};
        return a;
    }
    

提交回复
热议问题