fra*_*ans 8 c++ iteration containers pointers const
我有一个容器shared_ptr<>,例如a vector<shared_ptr<string>> v,我想迭代v指示const-ness.
这段代码:
vector<shared_ptr<string>> v;
v.push_back(make_shared<std::string>("hallo"));
...
for (const auto &s : v) {
*s += "."; // <<== should be invalid
}
Run Code Online (Sandbox Code Playgroud)
看起来像我想要做的(表明那s是const)但当然它不会成为字符串const.
是否有一种优雅的方法来迭代一个容器,shared_ptr明确表示内容不会被修改?
就像是
for (shared_ptr<const string> s : v) {
*s += "."; // <<== will not compile
}
Run Code Online (Sandbox Code Playgroud)
(但是这段代码不会因其他原因编译:))
编辑:
我犯了一个错误.最初我正在声明一个引用,这会导致编译器错误
for (shared_ptr<const string> &s : v) { // <<== does not compile
...
}
Run Code Online (Sandbox Code Playgroud)
如果您声明shared_ptr<const string>该示例有效.在我看来,这是一个很好的权衡,但这样一来指针被复制,这在循环中耗费大量代码和大容器时会很费时间.
Lig*_*ica 10
这是C++的一个众所周知的限制,有些人不认为这是一个限制.
你想迭代const,但不可变指针并不意味着不可变的指针.
类型shared_ptr<string>和类型shared_ptr<const string>实际上是无关的.
for (const auto& ptr : v) {
const auto& s = *ptr;
s += "."; // <<== is invalid
}
Run Code Online (Sandbox Code Playgroud)
只是不要修改它.