Which is correct: vector<const string>
OR const vector<string>?
I want to create an std::vector
of std::string
s, and I won't make changes to it.
But I am not sure which of the two ways is better and why.
A const vector will return a const reference to its elements via the [] operator . In the first case, you cannot change the value of a const int&. In the second case, you cannot change the value of a reference to a constant pointer, but you can change the value the pointer is pointed to.
const vector<string>: Cannot change anything about the vector.
You can't put items into a const vector, the vectors state is the items it holds, and adding items to the vector modifies that state. If you want to append to a vector you must take in a non const ref. Show activity on this post. If you have a const vector it means you can only read the elements from that vector.
If your only choices are those two and you want the program to compile, use const std::vector<std::string>
.
If you don't mind compilation errors (both on GCC4.8 and Clang), probably due to the fact that const std::string
does not meet the requirement of CopyAssignable (prior to C++11) or MoveAssignable (since C++11), even though, apparently, it's mostly because it's not Destructible
, use std::vector<const std::string>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With