std::vector: vec.data() or &vec[0]

后端 未结 5 2057
名媛妹妹
名媛妹妹 2020-12-14 15:31

When you want access a std::vector as a C array you can choose from at least four different ways, as you can see in this example:

#include 
#         


        
5条回答
  •  执笔经年
    2020-12-14 16:01

    Using &vec[0] is the most common although, I agree, does look a little odd. One thing to keep in mind for the future. If your vector happens to be a vector of objects whose class overloads the operator&(), realize that this will cause strange behavior if you call &vec[0].

    This will not get the starting address of the first item in the internal contiguous array of objects, it will return whatever vec[0].operator&() would return. Most if not all of the time, that's not the address you're looking for (Jedi hand wave).

    A good example of this is ATL's CComPtr. It overloads operator&() so storing it in a vector can be problematic. To get around this, ATL has a CAdapt template class which can be used to hide the operator&() on CComPtr

提交回复
热议问题