Mat*_*out 1 c++ direct3d const const-correctness direct3d11
我不明白为什么允许这样做:
void Renderer::UpdateTextureFromArray(unsigned int* colors, unsigned int size, TextureData* textureData) const
{
D3D11_MAPPED_SUBRESOURCE ms;
this->deviceContext->Map(textureData->texture, 0, D3D11_MAP_WRITE_DISCARD, NULL, &ms);
memcpy(ms.pData, colors, sizeof(unsigned int) * size * size);
this->deviceContext->Unmap(textureData->texture, 0);
}
Run Code Online (Sandbox Code Playgroud)
我创建了UpdateTextureFromArray函数const,但我仍然允许在其成员上调用非const函数?
在这种情况下,将函数标记为const是不好的风格?
编辑:澄清一下,如果我有像这样的const函数,它是否对社会"撒谎"?在完美的世界中,这段代码无法编译,对吧?
大概deviceContext是指针数据成员,因此const方法无法修改指针.但是允许修改指针指向的对象:
struct Bar {
void bar() {} // non const method
};
struct Foo {
Foo() : p(0) {}
void foo() const { p->bar();} // const method calling non-const method of Bar
Bar* p;
};
int main()
{
const Foo f;
f.foo(); // OK, Foo::p is not modified
}
Run Code Online (Sandbox Code Playgroud)