什么是返回引用一个恒定大小的指针数组的最好的方法? [英] What is the best way to return reference to a constant sized array of pointers?
问题描述
我有一个声明为类成员的指针数组,如下所示:
I have an array of pointers declared as a class member like this:
class Bar
{
private:
static constexpr int SIZE = 10;
Foo* m[SIZE];
}
在我的一个类方法中,我想返回一个指针优选地,参考)到该阵列。数组在编译时有一个已知的大小,但我跟踪我有多少项目我放在那里(它是一个缓冲区的东西)。
In one of my class methods, I would like to return a pointer (or preferably, a reference) to this array. The array has a known size at compile time, but I am keeping track of how many items I have put in there (it is a buffer of stuff).
在C ++ 11中返回此数组的引用的最佳方法是什么?
What is the best way to return a reference to this array in C++11 ?
我试过的东西:
GetArray(Foo* &f[], unsigned &size) const
我喜欢语法,因为它清楚地表明引用值是一个指针数组, :声明为类型为Foo的引用数组*
I like the syntax because it makes it clear that the reference value is an array of pointers, but this gives a compiler error: Declared as array of references of type Foo*
GetArray(Foo** &f, unsigned &size) const
{
f = m;
size = mSize;
}
给我:错误:分配到 Foo ** 'from不兼容的类型Foo * const [10]
。将 mFoo
转换为(Foo **)
可以缓解错误,但是IMHO不太优雅。
Gives me: Error: assigning to Foo **' from incompatible type Foo *const[10]
. Casting mFoo
to (Foo**)
alleviates the error, but IMHO, this is not elegant.
推荐答案
没有人使用 std :: array
替换:
class Bar
{
std::array<Foo *, 10> m;
public:
std::array<Foo *, 10> & getArray() { return m; }
std::array<Foo *, 10> const & getArray() const { return m; }
};
在我看来,这比你要跳过的C数组版本。
This seems to me a lot simpler than the hoops you have to jump through to use your C-style array version.
为了避免代码重复,你可以 typedef std :: array< Foo *,10> FooArray;
。
To avoid code duplication you could typedef std::array<Foo *, 10> FooArray;
.
同时具有 const
code> const 实现是返回引用或指针的访问器函数的常见模式。 (如果你的访问器返回值是不需要的,当然)。
The technique of having both a const
and a non-const
implementation is a common pattern for accessor functions which return a reference or a pointer. (It's not required if your accessor returns by value, of course).
这篇关于什么是返回引用一个恒定大小的指针数组的最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!