我有一个容器 shared_ptr<>
,例如一个vector<shared_ptr<string>>
v
我想遍历 v
表示常量。
这段代码:
vector<shared_ptr<string>> v;
v.push_back(make_shared<std::string>("hallo"));
...
for (const auto &s : v) {
*s += "."; // <<== should be invalid
}
看起来 就像我想做的(表示 s
是 const
)但当然它不会生成字符串 const
.
有没有一种优雅的方法来遍历 shared_ptr
的容器?这表明内容不会被修改?
有点像
for (shared_ptr<const string> s : v) {
*s += "."; // <<== will not compile
}
(但由于其他原因这段代码无法编译:))
编辑:
我错了。最初我是在声明一个引用,这导致编译器错误
for (shared_ptr<const string> &s : v) { // <<== does not compile
...
}
如果你声明一个 shared_ptr<const string>
这个例子有效。在我看来,这是一个很好的权衡,但这种方式会复制指针,这在代码很少和容器很大的循环中可能很耗时..
最佳答案
这是 C++ 的一个众所周知的限制,有些人并不认为这是一个限制。
您想迭代 const
ly,但不可变指针并不意味着不可变指针。
类型shared_ptr<string>
和类型 shared_ptr<const string>
实际上是无关的。
选项 1
for (const auto& ptr : v) {
const auto& s = *ptr;
s += "."; // <<== is invalid
}
选项 2
只是不要修改它。
关于c++ - 基于范围的 for 循环与 const shared_ptr<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34515918/