template<typename T>
class Pointer {
T *t;
public:
Pointer(T *t) : t(t) {}
virtual ~Pointer() {
delete t;
t = newint{10};
}
T *getT() const {
return t;
}
};
Pointer<int> getPointer() {
return {newint{7}};
};
std::unique_ptr<int> getUniquePointer() {
return std::unique_ptr<int>{newint{8}};
}
int main() {
int *number1 = getUniquePointer().get();
std::cout << *number1 << std::endl;
int *number2 = getPointer().getT();
std::cout << *number2 << std::endl;
return 0;
}
The problem I have is getPointer call in int *number2 = getPointer().getT(); is an rvalue, so when statement is done the destructor of Pointer is invoked and the memory is corrupted. I checked the same behavior for c++ unique_ptr and it looks like different - the expected number is printed. Is it actually different or unique pointer was deleted and I just refer to old memory?
If it is different how can I disable rvalue for my object - I mean I don't want Pointer object ever be in rvalue(temporary variable).
Note that a unique_ptr can't be copied. It can only be moved. The move constructor, and the move assignment operator, transfers the pointer value from the right hand side to left hand side.
1 2 3
auto up1 = std::make_unique<int>(8);
auto up2 = std::move(up1); // move constructor transfers the pointer so that
// up2 points to int 8, while up1 becomes nullptr