我有一个类必须返回一个constant一些指向软件上层的指针的视图。
在内部,指针必须是非常量,因为类需要在内部操作对象。
我没有看到任何选项可以在不复制所有指针的情况下向更高级别的客户端提供指针的常量视图。这看起来很浪费。如果我管理数百万个对象怎么办?
有没有更好的办法?
这是一些示例代码:
#include <vector>
#include <iostream>
class example {
public:
example() {
bytePtrs_.push_back(new char);
*bytePtrs_[0] = '$';
}
// I want to do this, but compiler will not allow
// error: could not convert ‘((example*)this)->example::bytePtrs_’ from ‘std::vector<char*>’ to ‘std::vector<const char*>’
std::vector<const char*> getPtrs() {
return bytePtrs_;
}
// Must make wasteful copy
std::vector<const char*> getPtrs() {
std::vector<const char*> ret;
for (auto &ptr : bytePtrs_)
ret.push_back(ptr);
return ret;
}
private:
std::vector<char*> bytePtrs_;
};
int main() {
example e;
std::vector<const char*> bytePtrs = e.getPtrs();
std::cout << bytePtrs[0] << std::endl;
}
您可以使用以下方法执行此操作std::实验::propagate_const https://en.cppreference.com/w/cpp/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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)