Domanda

I don't understand why this is allowed:

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);
}

I made the UpdateTextureFromArray function const, yet I'm still allowed to call a non-const function on its members?

In this case, is it bad style for me to label the function as const?

EDIT: To clarify, is it "lying" to society if I have a function like this const? In a perfect world, this code wouldn't compile, right?

È stato utile?

Soluzione

Presumably deviceContext is a pointer data member, so a const method cannot modify the pointer. But is is allowed to modify the object the pointer points to:

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
}

Altri suggerimenti

You're not calling a non-const function on its member, you're dereferencing its member (which doesn't modify it, so is allowed to be done with a const pointer) and then calling a non-const member on the result of that dereference.

You are not calling non-const function on its members, you are accessing a pointer (which is const) which is pointing to a non-const object. You are thereby able to call non-const functions on it.

Regarding style, a const method is a method that doesn't change the state of the object from the users viewpoint. So you have to consider yourself if this pointer access does this or not. Some classes are candidates for parallelization in which case const methods are regarded as safe methods to parallelize as they are supposed to be without side effects.

So to qualify a method for const, I would suggest that it:

  • Isn't a candidate for parallelization and have no user visible side effects
  • Is a candidate for parallelization but have proper synchronization or no side effects at all.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top