Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is &vec[0] defined behavior for a std::vector vec?

Tags:

c++

c++11

I see this a lot:

std::vector<Something> vec;
do_something_with_vec(vec);
Something *arr=&vec[0];
do_something_that_needs_carray(arr);

I mean, a vector will probably use an array internally so I see why this works, I'm just wondering whether or not this is defined behavior (like, is an implementor allowed to run an implementation of std::vector with which this would break).

If there are conflicts between the standards, I'm interested in what the C++11 standard says.

like image 380
Cubic Avatar asked Dec 21 '12 19:12

Cubic


People also ask

What type of word is is?

Is is what is known as a state of being verb. State of being verbs do not express any specific activity or action but instead describe existence. The most common state of being verb is to be, along with its conjugations (is, am, are, was, were, being, been).

What are the meanings of is?

present tense third-person singular of be.

What is the origin of the word is?

From Middle English is, from Old English is, from Proto-West Germanic *ist, from Proto-Germanic *isti (a form of Proto-Germanic *wesaną (“to be”)), from Proto-Indo-European *h₁ésti (“is”).

Why and is used?

And is a coordinating conjunction. We use and to connect two words, phrases, clauses or prefixes together: Televisions and computers are dominating our daily life. ( noun + noun) I have to shower and change. (


1 Answers

Yes it is allowed, if the std::vector is not empty. If the vector is empty, vec[0] will evoke Undefined Behavior.

std::vector is required to store elements contiguously.

There is also data() method, but it is C++11 only.

Important:

This will not work on std::vector<bool> (bit-efficient specialization). But it is also not a container, and IMO it should be deprecated.

like image 150
milleniumbug Avatar answered Sep 21 '22 12:09

milleniumbug