1

For example, I have such a smart pointer:

template <typename T>
class SmartPointer
{
public:
    ....
    T* operator & () { return m_p; } 
private:
    T* m_p;  
}

void foo()
{
    std::vector<SmartPointer<int> >vec;
    vec.push_back(....);
    vec.resize(.....);
    ......
}

Is this usage safe? I try it in MINGW4.4, It work ok....

In fact, those code is use work for COM, when I wanted to get a object, I need to do these

SmpartPointer<COMObj> spObj;
HRESULT hr = xxxxx->QueryInterface(&spObj);

then i wanted to store the pointer in a vector, so

std::vector<SmpartPointer<COMObj> >vec;
.....    
Chen
  • 119
  • 9
  • I don't see why it shouldn't be safe? `vector` are templated, so anything you do will be based on a template should be as safe as anything else. – Mats Petersson Aug 30 '13 at 09:27
  • 7
    Why would you even want to do that? If `p` were a normal pointer, you wouldn't expect `&p` to return the pointer. Giving overloaded operators different semantics is a good way to cause bugs later. – Dan Hulme Aug 30 '13 at 09:28
  • If the implementation of `std::vector` requires a raw pointer to its data internally, I'd expect it to use `std::addressof` or `allocator::address` to obtain it. – Angew is no longer proud of SO Aug 30 '13 at 09:30
  • Overloading operator& is questionable in most, if not all cases. It's counterintuitive and does not make sense for smartpointers. – Arne Mertz Aug 30 '13 at 09:33
  • 2
    I don't remember any requirements that client classes of `std::vector` *not* overload the operator, so I assume it's fine. Your use of operator overloading is the archetype of a Bad Idea, though. – Kerrek SB Aug 30 '13 at 09:33
  • Related: http://stackoverflow.com/questions/2719832/why-is-overloading-operator-prohibited-for-classes-stored-in-stl-containers – gx_ Aug 30 '13 at 09:42
  • 2
    you may want to use 'operator T*()' – Jarod42 Aug 30 '13 at 10:02

1 Answers1

3

In C++03, there is no explicit requirement that value types in containers do not overload unary operator&; however per 23.1p3 the objects stored are required to model CopyConstructible (20.1.3p1, Table 30). This in turn requires that the expression &t should yield a value of type T * that denotes the address of t. So overloaded unary operator& is permissible, but only if it has the "correct" return type and returns the correct value.

Your operator& is invalid; it should return SmartPointer<T> *.

In C++11 this was relaxed (through the use of std::addressof) so unary operator& can have any type and return any value.

In all versions of the standard, the type parameter of complex and valarray must not overload unary operator&; this is to allow them to be treated as contiguous storage.

ecatmur
  • 152,476
  • 27
  • 293
  • 366