1

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?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Dale Wilson
  • 9,166
  • 3
  • 34
  • 52
  • This shouldn't be the case. The conversion of `unique_ptr` to `bool` should be marked `explicit`. – pmr May 10 '12 at 15:51

2 Answers2

4

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.

pmr
  • 58,701
  • 10
  • 113
  • 156
1

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.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • But that is not what should happen. The operator should be explicit and there should be no conversion here. This is a bug. – pmr May 17 '12 at 21:15