0

Why is wp5 not pointing to an Integer whose value is 50?

#include <memory>
#include <iostream>
#include "DoubleLinkedList.h"

class Integer {
private:
    int number;
public:
    Integer(int number) : number(number) {}

    int get() { return number; }

};

int main() {

    Integer i1(10);
    Integer i2(20);
    i1 = i2;
    std::cout << "i1 = " << i1.get() << std::endl;
    Integer* i3 = new Integer(30);
    std::shared_ptr<Integer> sp3 = std::make_shared<Integer>(i1);
    std::shared_ptr<Integer> sp4 = std::shared_ptr<Integer>(new Integer(40));
    std::weak_ptr<Integer> wp5 = std::shared_ptr<Integer>(new Integer(50));
    std::weak_ptr<Integer> wp6 = sp4;



    return 0;
}

Is there a way to create a shared_pointer<Integer> or a weak_pointer<Integer> that use *i3 as a basic pointer to the Integer(30)?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Antonio Santoro
  • 827
  • 1
  • 11
  • 29
  • 1
    Because you initialized it from a temporary object that gets immediately destroyed. See the duplicate question for more information. – Sam Varshavchik Jul 15 '19 at 10:47
  • You can't. That's not how weak pointers work. Unless you can point a finger to somewhere in your code where you have a shared pointer variable referencing a given object, it is logically impossible for a weak pointer to the same object to exist at the same time. Where is the shared ptr which holds a strong reference to your "Integer(30)", here? – Sam Varshavchik Jul 15 '19 at 11:42

0 Answers0