基于范围的for循环与const shared_ptr<> [英] range based for loop with const shared_ptr<>
问题描述
我有一个包含 shared_ptr<>
的容器,例如a 向量< shared_ptr< string>>
v
并且我想迭代 v
表示常量。
此代码:
矢量< shared_ptr< string> v;
v.push_back(make_shared< std :: string>(hallo));
...
for(const auto& s:v){
* s + =。 //<< == should be invalid
}
/ em>喜欢我想做的(指示 s
是 const
),但是当然不会是否有一个优雅的方法来遍历 shared_ptr 的容器。
const / code>这清楚表明内容不会被修改?
像
for(shared_ptr< const string> s:v){
* s + =。 //<< == will not compile
}
不编译为其他原因:))
编辑:
错误。最初我是声明一个引用,导致编译器错误
for(shared_ptr< const string>& s:v) {//<< ==不编译
...
}
如果你声明一个 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
只是不要修改它。
I have a container with shared_ptr<>
, e.g. a vector<shared_ptr<string>>
v
and I'd like to iterate over v
indicating const-ness.
This code:
vector<shared_ptr<string>> v;
v.push_back(make_shared<std::string>("hallo"));
...
for (const auto &s : v) {
*s += "."; // <<== should be invalid
}
looks like what I want to do (indicating that s
is const
) but of course it does not make the string const
.
Is there an elegant way to iterate over a container of shared_ptr
which makes clear that the content won't be modified?
Something like
for (shared_ptr<const string> s : v) {
*s += "."; // <<== will not compile
}
(but this code would not compile for other reasons :))
Edit:
I made a mistake. Originally I was declaring a reference, which results in a compiler error
for (shared_ptr<const string> &s : v) { // <<== does not compile
...
}
If you declare a shared_ptr<const string>
the example works. In my eyes this is a good trade-off but this way the pointer gets copied which can be time consuming in loops with little code and big containers..
This is a well-known limitation of C++ that some don't consider to be a limitation.
You want to iterate const
ly, but an immutable pointer doesn't imply an immutable pointee.
The type shared_ptr<string>
and the type shared_ptr<const string>
are effectively unrelated.
Option 1
for (const auto& ptr : v) {
const auto& s = *ptr;
s += "."; // <<== is invalid
}
Option 2
Just don't modify it.
这篇关于基于范围的for循环与const shared_ptr<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!