我一直在思考STL容器及其元素的持久性(有些人可能会说是未经证实,让我们看看会发生什么).
我一直在寻找对此的讨论,但结果却令人惊讶地稀疏.所以我不一定在这里寻找一个明确的答案,我会对一个让我的脑袋再次移动的讨论感到高兴.
假设我有一个类将std :: strings保存在std :: vector中.我的类是一个从字典文件中读取单词的字典.它们永远不会改变.因此将其声明为谨慎似乎是谨慎的
std::vector<const std::string> m_myStrings;
Run Code Online (Sandbox Code Playgroud)
但是,我读过散乱的注释,你不应该在std :: vector中使用const元素,因为元素需要是可赋值的.
题:
有没有在std :: vector中使用const元素的情况(不包括hacks等)?
const元素是否在其他容器中使用?如果是这样,哪些,什么时候?
我主要是在这里讨论值类型作为元素,而不是指针.
#include <functional>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class A
{
public:
void doStuff(function<void (const string *)> func) const
{
cout << "Const method called" << endl;
for(const auto& i_string : m_vec)
func(i_string);
}
void doStuff(function<void (string *)> func)
{
cout << "Non-const method called" << endl;
doStuff([&func](const string *str)
{
auto mutableString = const_cast<string *>(str);
func(mutableString);
});
}
private:
vector<string *> m_vec;
};
int main()
{
auto a = A{};
a.doStuff([](string *str){
*str = "I modified …
Run Code Online (Sandbox Code Playgroud)