I don't think I've understood the concept of smart pointers correctly.
Have a look at this MWE:
// Example program
#include <iostream>
#include <memory>
#include <string>
struct P{
float x, y;
P() : x(0.f), y(0.f){}
P(float x, float y) : x(x), y(y){}
P(P&& q) : x(q.x), y(q.y){}
P& operator=(P&& q){
x = q.x;
y = q.y;
return *this;
}
P& operator=(const P&) = delete;
P(const P&) = delete;
};
std::ostream& operator<<(std::ostream& out, const P& p){ out << p.x << " / " << p.y; return out;}
int main(){
P p1{1.f, 0.f};
P p2{2.f, 0.f};
std::unique_ptr<P> p1Ptr(std::make_unique<P>(std::move(p1)));
P* p2Ptr = &p2;
p1 = std::move(P{1.f, 1.f});
p2 = std::move(P{2.f, 2.f});
std::cout << " p1: " << p1 << "\n";
std::cout << "*p1: " << *p1Ptr << "\n";
std::cout << "*p1: " << *(p1Ptr.get()) << "\n";
std::cout << " p2: " << p2 << "\n";
std::cout << "*p2: " << *p2Ptr << std::endl;
}
Output:
p1: 1 / 1
*p1: 1 / 0
*p1: 1 / 0
p2: 2 / 2
*p2: 2 / 2
I would have expected the std::unique_ptr
to also see the value change of p1
. However, this is not the case. How can I achieve this?