What should std::vector::data() return if the vector is empty?

后端 未结 4 1149
不思量自难忘°
不思量自难忘° 2020-12-01 23:30

According to the draft standard (23.3.6.4 vector data), data() points to the underlying array and [data(), data() + size()) must be a valid range:



        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 00:04

    There is a state that an object can be valid but unspecified:

    valid but unspecified state [§ 17.3]

    an object state that is not specified except that the object’s invariants are met and operations on the object behave as specified for its type

    [Example: If an object x of type std::vector is in a valid but unspecified state, x.empty() can be called unconditionally, and x.front() can be called only if x.empty() returns false. —end example]

    Reading the C++ standard, the state of data() is not specified when the vector is empty. So, the state is valid but unspecified state. Therefore, the returned value of data() when the vector is empty can be anything (null or a random value). It depends on implementation of the compiler.

    In this case, following the example in §17.3, you should call empty() before using data() to ensure that the returned value is as your expectation.

    if (!v.empty())
       do_something(v.data())
    

提交回复
热议问题