How could I copy the resource of unique_ptr?

1
2
3
std::unique_ptr<int> A(new int(4));
std::unique_ptr<int> B;
B = std::move(A);

I could "move" the resource to B, but how could I copy the resource
to B so B could have a copy of A?

I try it like this
1
2
std::unique_ptr<size_t> uPtr_1(new size_t(5) );
std::unique_ptr<size_t> uPtr_2(new size_t(*uPtr_1));

Is this safe?Could you introduce me better methods?
How could I know the type of the unique_ptr?
Thanks a lot
Last edited on
The second method is as safe as it gets. Line 2 will throw iff the copy constructor of the contained type throws.

1
2
3
template< typename T >
void contained_type( const std::unique_ptr<T>& )
{}


T is the contained type.

OR

std::unique_ptr<T>::element_type is a typedef for T.

std::unique_ptr<> also has its own move constructor, however both that and your first block above, while equivalent,
are not the same as your second code block. The first block creates only a single int; your second example creates two.
Thanks a lot

I have two more questions
1: is gcc4.5(mingw) realize the move constructor and move assignment of the stl containers already?
I saw the emplace_backmember function when I enable gcc to follow the C++0x
atleast vector and string have the emplace_backmember function

2: looks like gcc4.5(mingw) do not fully implement the unique_ptr yet, because I cannot sort the
elements of the unique_ptr by the std::sort. Is gcc4.6 fix this problem?

Last edited on
Well, I can't really answer either of your questions because I don't use gcc 4.5 or mingw. However, I can say
that the C++0x standard isn't ratified yet, so any compiler implementation that exists today may change in
the future if more edits are made to the standard before ratification.
Topic archived. No new replies allowed.