【发布时间】:2017-09-29 10:36:41
【问题描述】:
我有以下代码:
#include <vector>
struct TestStruct {
std::vector<float> float_vect;
std::vector<bool> bool_vect;
};
void func(const TestStruct & test)
{
const float * p1 = test.float_vect.data(); //<--- this line works fine
const bool * p2 = test.bool_vect.data(); //<--- on this line error happens
}
int main()
{
TestStruct test;
func(test);
}
错误信息:
将 'const std::vector' 作为 'void std::vector::data() [with _Alloc = std::allocator]' 的 'this' 参数传递会丢弃限定符 [-fpermissive]
std::vector 的data() 方法指定了const。
为什么这种方法在浮点向量上运行良好,而在布尔向量上引发错误?
【问题讨论】:
-
我不认为标准规定有任何
std::vector<bool>::data()成员函数。 -
我从来没有仔细观察过它,但是std::vector<bool> 说
[...]std::vector<bool> is a possibly space-efficient specialization of std::vector for the type bool.[...]和[...]The manner in which std::vector<bool> is made space efficient (as well as whether it is optimized at all) is implementation defined.[...]所以data()的内存布局是未知的。 -
我没有看到可用于
std::vector<bool>的data方法。