Consider the following code snippet:
class Owner {
public:
Owner(std::unique_ptr<int> ptr) : owned_pointer<int>(std:move(ptr)) {}
private:
std::unique_ptr<int> owned_pointer;
};
std::unique_ptr<int> ptr(new int);
int* ptr1 = ptr.get();
Owner new_owner(std::move(ptr));
Is it safe to assume that ptr1 is valid as long as new_owner stays in scope? It seems to work, but I can't find a specification that states that explicitly - is it undefined behavior/implementation specific and just happen to work for me, or the code posted above is valid (ptr1 is guaranteed to point to moved pointer as long as it stays alive)?
unique_ptr<int>
stores a value that is of typeint*
. On destruction, it callsdelete
on it (through a traits class).ptr.get()
returns a copy of theint*
.new_owner
transfers ownership of thatint*
, so the oldunique_ptr
won'tdelete
it and the new one will. Nothing magic should be going on. Unless you are looking for a standardese tea leaf reading and are interested in possible holes/errors in the standard? – Yakk - Adam Nevraumontint*
). This isn't like iterator abstractions around lifetime issues with vector, where practical and standard defined behavior can and probably should differ. So any standard tea leaf reading that disagrees would just mean there is a bug in the standard. I suppose such a bug in the standard, if not noticed, might lead gcc to implement the bug in a future iteration? – Yakk - Adam Nevraumont