nekitip
nekitip

Reputation: 365

How to make function return pointer to an array or object in C++?

I'm confused with a lot of answers found about what is a simple thing in other languages. I would like to get a reference to an object contained in class or struct. I've come up to using one of two different functions (here - getData()).

Question:

So, I am not sure which one to use, they appear to do the same thing. Other thing, is there some reason I should care because it's a union? And the most important question here is - I'm not sure about delete part I found in some answers, which scares me that this code example I've shown is not complete and will cause some memory leaks at some point.

#include <iostream>
#include <stdint.h>

using namespace std;

class settings_t {
  private:
  static const  long b1 =0;
    uint8_t setmap;
  public:
    uint8_t myBaseID; 
    uint8_t reserved1;
    uint8_t reserved2;
};  

class test1 {
  public: //actually, I want this to be private
    long v1;
    settings_t st;
    union {
      uint8_t data[4];
      uint32_t m1;
      settings_t st1;
    };
  public:
    uint8_t * getData() {
      return data;
    }
    uint8_t (&getData2())[4] {
      return data;
    }
};

int main() {
  test1 t1;
  t1.data[2]=65;
  uint8_t *d1 = t1.getData();
  cout<<" => " << d1[2];
  d1[2]=66;
  uint8_t *d2 = t1.getData2();
  cout<<" => " << d2[2];
}

Upvotes: 0

Views: 88

Answers (1)

Serge
Serge

Reputation: 12354

The main difference of c++ from languages like c# or java is that it does not provide you with built in memory management (not a managed language). So, if the program allocates memory in c++, it is a responsibility of the program to release the memory when it is not needed. so, delete in your answers is based on this requirement.

However in you case, the getData() function returns a pointer to the data which is a part of the class test1. This is an array and the array will exist as long as the object of this class exist. Both versions of the getData will work.

You did not use any dynamic data allocation, the object t1 of type test1 was allocated on the stack of the main function and would exist till your program exits. You should not worry about 'delete'.

The difference between two methods you use is that the first method does not care about the array size it returns, whether the other does. For that reason the second methods has very limited practical use, but provides better syntactic checking.

Upvotes: 1

Related Questions