| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
shared_ptr Deep Copy
How can I get copy of a container which has shared pointers. In the following exmaple I would like to get a copy of vecIntPtr vector so that any changes that I make in the copy, do not affect values pointed by the pointers in vecIntPtr. I tried doing that by creating vecIntPtrTemp but it did not work.
Thanks in advance! #include <iostream> #include <vector> #include <boost/shared_ptr.hpp> int main() { typedef boost::shared_ptr<int> intPtr; std::vector<intPtr> vecIntPtr; intPtr x(new int(10)); vecIntPtr.push_back(x); std::cout << *vecIntPtr[0] << std::endl; std::vector<intPtr> vecIntPtrTemp(vecIntPtr); *vecIntPtrTemp[0] = 100; std::cout << *vecIntPtrTemp[0] << std::endl; std::cout << *vecIntPtr[0] << std::endl; return 0; } Output: 10 100 100 |
|
#2
|
|||
|
|||
|
When you create a pointer all you are doing is creating a reference to a piece of memory. When you copy that pointer you get a variable that also references that same piece of memory. So when you change what either one points to you still change the same original value. To avoid affecting the original value you need to create a new variable of that type not just a pointer to it and change the value of that.
-KM- |
|
#3
|
|||
|
|||
|
container of pointers
In this case its easy to copy the values in int pointer and create a new vector.....My problem is that
I have vector of a object which is very big and which has another object insid it so I was wondering if there is any smart pointer which could let me have the speed of container of pointers and give me the ability to get a new copy of container of pointers when I need one for some specific algorithm where I need to backtrack if I am not satisfied with the new changes. |
|
#4
|
|||
|
|||
|
I think you probably need to write the smart container yourself if speed is the issue.
Creating dynamic objects is typically more costly in terms of the memory allocation than the operations performed on the object. I would write templates that contains duplicates members for back tracking. _____________________________________________________ Sharon White |
|
#5
|
|||
|
|||
|
thanks Sharon,
I think duplicate members will work out fine for me .......... creating a smart container is something which I don't want to attempt right now due to my limited knowledge of templates......... Quote:
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > shared_ptr Deep Copy |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|