【发布时间】:2021-04-11 16:09:49
【问题描述】:
假设我有这个代码。哪种方法更好?
// Method 1
std::size_t size()
{
// m_myVector is of type std::vector<MyClass*> in all examples
return m_myVector.size();
}
// Method 2
std::vector<MyClass*>::size_type size()
{
// m_myVector is of type std::vector<MyClass*> in all examples
return m_myVector.size();
}
第一种方法适用于 99% 的情况,但当然也有可能向量的大小不是 std::size_t 类型。也就是说,我们可以只依靠软件分析工具告诉我们向量大小的返回类型发生了变化。
第二种方式将向量的实现细节暴露给调用者。这会破坏封装吗?我不知道,你告诉我!
这是另一个更复杂的例子。哪种方法更好?
void doFoo(const SomeClass& someObject)
{
// These could be ints or size_types... Feel free to use your imagination
std::size_t firstCount = someObject.getFirstCount();
for (std::size_t i = 0U; i < firstCount; ++i)
{
foo(firstCount);
}
}
void doFoo2(const SomeClass& someObject)
{
// I thought I'd provide another example to help your imagination :)
std::vector<MyClass*>::size_type secondCount = someObject.getSecondCount();
for (std::vector<MyClass*>::size_type i = 0U; i < secondCount; ++i)
{
foo(secondCount);
}
}
void doFoo3(const SomeClass& someObject)
{
// The correct styling would be: NotMyClass*
// But I really wanted to emphasize this was different from above, so I ALL CAPPED IT
std::vector<NOTMYCLASS*>::size_type thirdCount = someObject.getThirdCount();
for (std::vector<NOTMYCLASS*>::size_type i = 0U; i < thirdCount; ++i)
{
foo(thirdCount);
}
}
// Method 1
void foo(std::size_t index)
{
// m_myVector is of type std::vector<MyClass*> in all examples
m_myVector.at(index)->doLotsOfStuff();
}
// Method 2
void foo(std::vector<MyClass*>::size_type index)
{
// m_myVector is of type std::vector<MyClass*> in all examples
m_myVector.at(index)->doLotsOfStuff();
}
好的,这是一个很长的例子,所以我将解释发生了什么。 doFoo()、doFoo2() 和 doFoo3() 都调用 foo(),在第一个实现中接收 std::size_t,在第二个实现中接收 std::vector<MyClass*>::size_type。
doFoo() 将std::size_t 传递给foo(),因此foo() 的第一个实现在这里更有意义,但是我们索引一个std::vector<MyClass*>,它期待一个std::vector<MyClass*>::size_type。如果 size_type 未定义为 std::size_t,则不是特别好。
doFoo2() 将std::vector<MyClass*>::size_type 传递给foo(),所以foo() 的第二个实现在这里工作得很好。除了将私有向量的实现细节暴露给调用者之外,没有其他抱怨。最后我想我们需要include a separate header for MyClass。
doFoo3() 将std::vector<NOTMYCLASS*>::size_type 传递给foo()... 而foo() 的实现都没有预料到这一点,因为foo() 关心的唯一向量是包含MyClass* 类型元素的向量.现在,作为一个学术问题,std::vector<NOTMYCLASS*>::size_type 总是与std::vector<MyClass*>::size_type 相同吗?我实际上不知道这个问题的答案,但我一直在听到'yes' and 'no'。最后,再次出现封装问题(如果是问题的话)。
无论如何,感谢您对我的包容。想法?
【问题讨论】:
-
对于定义了
size_type的容器,使用它。否则,请使用size_t。 -
我不喜欢宣传
SomeClass中有vector,除非我必须这样做。这是一个更抽象的合理时间,将using size_type = <whatever>;添加到SomeClass,因此没有人知道或关心。此外,您几乎可以随时更改支持类型,而无需客户参与。 -
老实说,实际上
size_type总是与size_type相同。 -
为什么不使用
auto,它 100% 的时间都有效。 -
@NathanOliver C++98 :)
标签: c++ encapsulation c++98 size-t size-type