Array: saving objects or links

As a Java developer, I have the following question in C ++.

If I have objects of type A, and I want to store them in an array, should I just store pointers to objects or is it better to save the object itself?

In my opinion, it is better to store pointers, because: 1) You can easily delete an object by setting its pointer to zero 2) One saves space.

+5
source share
6 answers

Pointers or just objects?

You cannot put references in an array in C ++. You can create an array of pointers, but I would prefer the container and the actual objects, rather than pointers, because:

  • Inability to leak, exception safety is easier to handle.
  • - , .

, , ( , ) ( ) , ( , ), , . .

#include <vector>

struct foo {
  virtual void it() {}
};

struct bar : public foo {
  int a;
  virtual void it() {}
}; 

int main() {
  std::vector<foo> v;
  v.push_back(bar()); // not doing what you expected! (the temporary bar gets "made into" a foo before storing as a foo and your vector doesn't get a bar added)
  std::vector<foo*> v2;
  v2.push_back(new bar()); // Fine
}

, , .

.

NULL , / ( delete), , , . if- , :

// need to go out of our way to make sure there no NULL here
std::for_each(v2.begin(),v2.end(), std::mem_fun(&foo::it));

NULL , . , std::vector erase, , :

v2.erase(v2.begin());

v2.begin()+1 . " n- ", std::vector - - , , .

:

#include <utility>
#include <iterator>
#include <algorithm>
#include <iostream>

int main() {
  int arr[] = {1,2,3,4};
  int len = sizeof(arr)/sizeof(*arr);
  std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;

  // remove 2nd element, without preserving order:
  std::swap(arr[1], arr[len-1]);
  len -= 1;
  std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;

  // and again, first element:
  std::swap(arr[0], arr[len-1]);
  len -= 1;
  std::copy(arr, arr+len, std::ostream_iterator<int>(std::cout, " "));
  std::cout << std::endl;
}

, std::vector. , , , !

+7

, . ++ 3

Java . , , .

, . , . . , , , ,

+1

, ... -.

, :

  • NULL ++, NULL.
  • - ​​ .
  • ( ).
  • , , . , , - MOST (: ).
  • : STL (, ..) COPY - . , , , , , . STL .

, !:)

PS (EDIT): BOOST/TR1 (google them) / shared_ptr ( ), Java , , - .

+1

, ; , .

; , , . , ; , , .

Java, , ; , . new, - delete. - (shared_ptr , , unique_ptr, ), Boost.

+1

. () , , , .

, . . , , . :

  • NULL , ;
  • ;
  • .

- , , , .

0

aix:

If you want to store polymorphic objects, you should use smart pointers because the containers make a copy, and for derived types it only copies the base part (at least the standard ones, I think boost has several containers that work differently). Therefore, you will lose any polymorphic behavior (and any state of the derived class) of your objects.

0
source

All Articles