基于const shared_ptr的循环的范围<>

时间:2015-12-29 17:27:45

标签: c++ pointers iteration const containers

我有一个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
}

看起来就像我想要做的那样(表示sconst)但当然它不会使字符串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>示例有效。在我看来,这是一个很好的权衡,但这样一来,指针就会被复制,在使用少量代码和大容器的循环中耗费时间。

3 个答案:

答案 0 :(得分:10)

这是一个众所周知的C ++限制,有些人不认为这是一个限制。

你想迭代const,但是一个不可变的指针并不意味着一个不可变的指针。

类型shared_ptr<string>和类型shared_ptr<const string>实际上是无关的。

选项1

for (const auto& ptr : v) {
    const auto& s = *ptr;

    s += ".";   // <<== is invalid
}

选项2

不要修改它。

答案 1 :(得分:2)

这是答案。

但首先,布道:

指针及其指向的东西是两个独立的对象。或者,没有或两者都可以是const,而const指针只是意味着它不会指向不同的东西。如果指针对象是const,则可能不会通过(可能是非常量)指针更改对象。

话虽如此,我们(I)经常编写使用unique_ptrshared_ptr作为pimpl的值语义包装器对象。通常我们希望将包装器的常量传播给impl。

我相信c ++ 17会用它的propagate_const指针包装器来解决这个问题。

与此同时,您可以直接建立自己的:

#include <iostream>
#include <type_traits>
#include <memory>
#include <string>
#include <vector>

namespace traits
{
    template<class T> struct pointee;
    template<class T, class D>
    struct pointee<std::unique_ptr<T, D>> {
        using type = T;
    };

    template<class T>
    struct pointee<std::shared_ptr<T>> {
        using type = T;
    };

    template<class T> using pointee_t = typename pointee<T>::type;
}

template<class PointerType>
struct propagate_const
{
    using pointer_type = PointerType;
    using element_type = traits::pointee_t<pointer_type>;
    using value_type = std::decay_t<element_type>;
    using reference = value_type&;
    using const_reference = const value_type&;

    propagate_const(pointer_type p) : _ptr(std::move(p)) {}

    const_reference operator*() const {
        return *_ptr;
    }

    auto operator*()
    -> std::enable_if_t<not std::is_const<element_type>::value, reference>
    {
        return *_ptr;
    }

private:
    pointer_type _ptr;
};

template<class PointerType>
auto make_propagating_pointer(PointerType&& p)
{
    return propagate_const<PointerType>(std::forward<PointerType>(p));
}

int main()
{
    using namespace std;

    vector<propagate_const<shared_ptr<string>>> v;
    v.emplace_back(make_shared<string>("hello"));

    for (const auto& p : v)
    {
//        *p += " there";  // compile error
        cout << *p;
        cout << endl;
    }

    for (auto& p : v)
    {
        *p += " there";
        cout << *p;
        cout << endl;
    }

    return 0;
}

预期产出:

hello
hello there

这个非常简单,仅支持operator*,但添加一组完整的运算符是微不足道的。请注意,当指针对象是const时,我禁用了可变访问。

参考:http://en.cppreference.com/w/cpp/experimental/propagate_const

只是为了好玩,这里有一个shared_string类的完整示例,它在内部使用shared_ptr并正确传播constness。

#include <iostream>
#include <type_traits>
#include <memory>
#include <string>
#include <vector>

template<class PointerType>
struct propagate_const
{
    using pointer_type = PointerType;
    using element_type = std::remove_reference_t<decltype(*std::declval<PointerType&>())>;
    using reference = element_type&;
    using const_reference = const element_type&;

    propagate_const(pointer_type p) : _ptr(std::move(p)) {}

    const_reference operator*() const {
        return *_ptr;
    }

    auto operator*()
    -> std::enable_if_t<not std::is_const<element_type>::value, reference>
    {
        return *_ptr;
    }

private:
    pointer_type _ptr;
};

template<class PointerType>
auto make_propagating_pointer(PointerType&& p)
{
    return propagate_const<PointerType>(std::forward<PointerType>(p));
}

struct shared_string
{
    shared_string(std::string s) : _impl(std::make_shared<std::string>(std::move(s))) {};
    shared_string(std::shared_ptr<std::string> sp) : _impl(sp) {};
    shared_string(propagate_const<std::shared_ptr<std::string>> sp) : _impl(sp) {};

    auto& operator += (const std::string& s) {
        *_impl += s;
        return *this;
    }

    friend std::ostream& operator<<(std::ostream& os, const shared_string& ss) {
        return os << *(ss._impl);
    }

private:
    propagate_const<std::shared_ptr<std::string>> _impl;
};

template<class T, std::enable_if_t<std::is_const<T>::value>* = nullptr >
std::string check_const(T&)
{
    return std::string("const");
}

template<class T, std::enable_if_t<not std::is_const<T>::value>* = nullptr >
std::string check_const(T&)
{
    return std::string("not const");
}

int main()
{
    using namespace std;

    // a vector of mutable shared_strings
    vector<shared_string> v;

    // a vector of immutable shared_strings
    vector<const shared_string> cv;

    // make a shared_string
    v.emplace_back(make_shared<string>("hello"));

    // refer to the *same one* in cv
    cv.emplace_back(v[0]);

    for (const auto& p : v)
    {
//        *p += " there";  // immutable reference to mutable shared string - not allowed
        cout << check_const(p) << " " << p;
        cout << endl;
    }

    for (auto& p : v)
    {
        cout << check_const(p) << " " << p;
        p += " there";    // mutable reference to mutable shared string - allowed
        cout << " becomes " << p;
        cout << endl;
    }

    for (auto&p : cv)
    {
        cout << check_const(p) << " " << p;
//        p += " world";     // p is actually immutable because cv contains immutable objects
        cout << endl;
    }

    return 0;
}

预期产出:

const hello
not const hello becomes hello there
const hello there

答案 2 :(得分:1)

我会选择模板评估

template <class T,class F>
void forEach(const std::vector<std::shared_ptr<T>>& vec, F&& f){
  for (const auto& ptr : vec){
      if (ptr){
         f(std::cref(*ptr));
     }
  }
}

我在那里放了一个lambda函数,编译器可能会内联它,所以这里没有性能损坏。