Ron
Ron

Reputation: 24235

Address of and dereference on a pointer

I came across this function in 'The C++ programming language' book.

template<typename In, typename Out> 
Out uninitialized_move(In b, In e, Out oo) {  
    using T = Value_type<Out>; // assume suitably defined type function (§5.4.2.1, §28.2.4)  
    for (; b!=e; ++b,++oo) {  
        new(static_cast<void*>(&*oo)) T{move(*b)}; // move construct  
        b–>~T(); // destroy
    }  
    return oo; 
}

The placement new parameter is &*oo

Why does it need &* in that statement ? Why won't just passing 'oo' work?

Upvotes: 2

Views: 72

Answers (2)

iBug
iBug

Reputation: 37307

In case oo isn't a pointer and has no operator T*() overload, you can't pass it directly as a pointer.

Some class objects, particularly iterators (like std::vector::iterator), implements something like

SomeStuff& SomeClass::operator*(void);

so that they can be "dereferenced" as if they were pointers. This is called operator overloading.

If you want to pass it directly, you must ensure there's such a member function like

SomeClass::operator T*(void);

In this way such objects can be implicitly converted to the corresponding pointers by calling that function. Otherwise you have to "dereference" it and then take the address of the dereferenced object.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

Although you are correct about & and * cancelling each other out for pointers, uninitialized_move is a template function, so oo could be of non-pointer type that has a custom dereference operator *, e.g. an iterator.

For types like that an explicit "round-trip" is required to ensure that static_cast is applied to a pointer.

Upvotes: 1

Related Questions