Originally posted by Ansla
View Post
![Wink](https://www.phoronix.com/forums/core/images/smilies/wink.png)
void ProcessItem(const std::shared_ptr<Item> &item) { someOtherSmartPointer = item; }
void ProcessItem(const std::shared_ptr<Item> &item) { someOtherSmartPointer = item; }
void ProcessItem(const std::shared_ptr<Item> &item) { someOtherSmartPointer = item; }
std::shared_ptr<std::string> previous_message; void send_message(const std::shared_ptr<std::string> &msg) { previous_message = 0; std::cout << *msg << std::endl; previous_message = msg; } (...) send_message(std::shared_ptr<std::string>(new std::string("Hi"))); send_message(previous_message);
#include <memory> #include <iostream> std::shared_ptr<int> x; std::shared_ptr<int> y; void updatex(const std::shared_ptr<int> &newX) { x = newX; } void updatey(int *newY) { y = std::shared_ptr<int>(newY); } int main() { { std::shared_ptr<int> tmpx(new int(1)); std::shared_ptr<int> tmpy(new int(2)); updatex(tmpx); updatey(tmpy.get()); std::cout << "tmpx=" << *tmpx << std::endl; std::cout << "tmpy=" << *tmpy << std::endl; } std::cout << "x=" << *x << std::endl; std::cout << "y=" << *y << std::endl; return 0; }
tmp=1 tmp2=2 x=1 ==32677== Invalid read of size 4 ==32677== at 0x401215: main (in /home/andrei/Projects/smart_pointers/a.out) ==32677== Address 0x59790f0 is 0 bytes inside a block of size 4 free'd ==32677== at 0x4C28A5E: operator delete(void*) (vg_replace_malloc.c:387) ==32677== by 0x401330: main (in /home/andrei/Projects/smart_pointers/a.out) ==32677== y=2 ==32677== Invalid free() / delete / delete[] ==32677== at 0x4C28A5E: operator delete(void*) (vg_replace_malloc.c:387) ==32677== by 0x401578: std::shared_ptr<int>::~shared_ptr() (in /home/andrei/Projects/smart_pointers/a.out) ==32677== by 0x560D870: exit (in /lib64/libc-2.13.so) ==32677== by 0x55F50A3: (below main) (in /lib64/libc-2.13.so) ==32677== Address 0x59790f0 is 0 bytes inside a block of size 4 free'd ==32677== at 0x4C28A5E: operator delete(void*) (vg_replace_malloc.c:387) ==32677== by 0x401330: main (in /home/andrei/Projects/smart_pointers/a.out)
(...)
#include <memory> #include <iostream> std::shared_ptr<int> x; void resetX() { x = std::shared_ptr<int> (0); } void updatex(const std::shared_ptr<int> &newX) { resetX(); //code have side effects that do set the //reference count of X to zero //the referene to newX is wrong std::cout << "x=" << newX << std::endl; } void updatex_safe_and_slow(std::shared_ptr<int> newX) { resetX(); //code have side effects that do set the //reference count of X to zero, but you have still a safe copy std::cout << "x=" << newX << std::endl; } void main() { { x =std::shared_ptr<int> (new int(1)); updatex_safe_and_slow(x); } { x =std::shared_ptr<int> (new int(1)); updatex(x); } }
Comment