在 C++ 中提供指针恒定视图的更好方法

Wil*_*eld 2 c++

我有一个类必须返回一些指向软件上层的指针的常量视图。

\n

在内部,指针必须是非 const,因为类需要在内部操作对象。

\n

我没有看到任何选项可以在不复制所有指针的情况下向更高级别的客户端提供指针的常量视图。这看起来很浪费。如果我管理数百万个对象怎么办?

\n

有没有更好的办法?

\n

这是一些示例代码:

\n
#include <vector>\n#include <iostream>\n\nclass example {\npublic:\n  \n  example() {\n    bytePtrs_.push_back(new char);\n    *bytePtrs_[0] = \'$\';\n  }\n\n  // I want to do this, but compiler will not allow\n  // error: could not convert \xe2\x80\x98((example*)this)->example::bytePtrs_\xe2\x80\x99 from \xe2\x80\x98std::vector<char*>\xe2\x80\x99 to \xe2\x80\x98std::vector<const char*>\xe2\x80\x99\n  std::vector<const char*> getPtrs() { \n    return bytePtrs_; \n  }\n\n  // Must make wasteful copy\n  std::vector<const char*> getPtrs() { \n    std::vector<const char*> ret;\n    for (auto &ptr : bytePtrs_)\n      ret.push_back(ptr);\n    return ret; \n  }\n\nprivate:\n\n  std::vector<char*> bytePtrs_;\n};\n\nint main() {\n\n  example e;\n\n  std::vector<const char*> bytePtrs = e.getPtrs();\n\n  std::cout << bytePtrs[0] << std::endl; \n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Gal*_*lik 6

您可以使用std::experimental::propagate_const来执行此操作。

这会将指针的常量转发到所指向的对象上。

#include <experimental/propagate_const>

class example {
public:

//  using vector = std::vector<char*>>;
    using vector = std::vector<std::experimental::propagate_const<char*>>;

    example() {
        bytePtrs.push_back(new char);
        *bytePtrs[0] = '$';
    }

    vector const& getPtrs() const {
        return bytePtrs;
    }

private:

    vector bytePtrs;
};

int main()
{
    example e;

    example::vector const& bytePtrs = e.getPtrs();

    // dereference this or add a null terminator
    std::cout << *bytePtrs[0] << std::endl; // fine and dandy

    *bytePtrs[0] = 'x'; // compile error
}
Run Code Online (Sandbox Code Playgroud)