1

Right now I have two vectors of Object pointers

std::vector<Object*> vec1;
std::vector<Object*> vec2;

Lets say vec1 has two objects and vec2 has none. How would I move one of the objects in vec1 to vec2 without destroying the actual object? So, in the end both vectors are of size 1 and each have an object pointer.

Kaiser Wilhelm
  • 618
  • 9
  • 24
  • 2
    Could it be that the whole pointer/object/reference thing is still a bit unclear to you? Maybe you would benefit from reading a _[good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)_? – sbi Sep 29 '11 at 18:46

5 Answers5

2

You won't destroy the data pointed to (assuming there even is any) until delete is called. You can do something as simple as...

vec2.push_back(vec1[1]);
vec1.pop_back();
MGZero
  • 5,812
  • 5
  • 29
  • 46
  • `delete` also won't "destroy the pointer". Beyond that, it's impossible to tell what delete will do without knowing more about where the pointer came from. – Kerrek SB Sep 29 '11 at 19:32
1

You don't destroy the object. Take it out of vec1 and push_back to vec2. Even if you take it out of both, you don't destroy the object.

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106
0

Suppose you want to move the last Object* from vec1 to vec2:

vec2.push_back(vec1[1]);
vec1.pop_back();  // not destroying Object*

Suppose you want to move any arbitrary Object* to other vector then get its vector::iterator and copy it to the destination. Then you can use vector::erase() on it.

iammilind
  • 68,093
  • 33
  • 169
  • 336
0

As already pointed out, I think you may benefit from more understanding of pointers in general before attempting to do anything with them. You're not moving or doing anything with the object itself, you're moving around / creating new pointers to that object.

NuSkooler
  • 5,391
  • 1
  • 34
  • 58
0

If the vectors contained objects instead of pointers to objects and you wanted to move and not copy I believe you could use std::move which returns rvalue reference which is movable but not copyable.

There is SO question about move here: What is std::move(), and when should it be used?

Community
  • 1
  • 1
minus
  • 706
  • 5
  • 14