std::unique_ptr ostream inserter
-
07-06-2021 - |
Question
I have enabled unique_ptr in gcc 4.4.6 using the -std=c++0x option. It appears to be working quite well and is exactly what I needed -- a scoped pointer with a custom deleter.
However I did notice a problem.
typedef std::unique_ptr<X> XPtr;
XPtr ptr1(new X);
XPtr ptr2(new X);
std::cout << "ptr1 points to " << ptr1 << std::endl;
std::cout << "ptr2 points to " << ptr2 << std::endl;
displays: ptr1 points to 1 ptr2 points to 1
I think the ostream inserter is inserting the bool value.
The following fixes it, but I'm wondering if this shouldn't be part of the standard library.
template<typename Target, typename Deleter>
std::ostream & operator <<( std::ostream & out, const std::unique_ptr<Target, Deleter> & value)
{
// output the raw pointer
out << value.get();
return out;
}
So the question is: is this a limitation of the current unique_ptr implementation in gcc, or am I expecting too much from unique_ptr?
Solution
This seems to be a bug in the library shipped with gcc 4.4.6. The conversion is
explicit operator bool() const noexcept;
and shouldn't be triggered by trying to insert the pointer into an
ostream
. This should result in a compilation error and that is
exactly what happens on gcc 4.7.
Edit: gcc 4.4 did not support explicit conversion operators, hence this wasn't working back then. You should get a newer gcc version to really use C++11.
OTHER TIPS
The unique_ptr
has operator bool() const
defined, so what you are seeing is unique_ptr object being converted to the bool value. As you discovered, to print a pointer's address, you need to use the get()
method.