Constness of captured reference

An object can be captured by mutable reference, and changed inside a member function which takes the same object as const .

void g(const int& x, std::function<void()> f)
{
  std::cout << x << 'n';
  f();
  std::cout << x << 'n';
}

int main()
{
  int y = 0;
  auto f = [&y] { ++y; };
  g(y, f);
}

An object is mutated in a scope where it is const . I understand that the compiler can't enforce constness here without proving that x and y are aliases. I suppose all I'm looking for is confirmation that this is undefined behavior. Is it equivalent in some sense to a const_cast - using a value as non- const in a context where it should be?


Reference or pointer to const doesn't mean the referenced object cannot be modified at all - it just means that the object cannot be modified via this reference/pointer . It may very well be modified via another reference/pointer to the same object. This is called aliasing.

Here's an example that doesn't use lambdas or any other fancy features:

int x = 0;

void f() { x = 42; }

void g(const int& y) {
  cout << y;
  f();
  cout << y;
}

int main() {
  g(x);
}

There's nothing undefined going on, because the object itself is not const , and constness on aliases is primarily for the user's benefit. For thoroughness, the relevant section is [dcl.type.cv]p3 :

A pointer or reference to a cv-qualified type need not actually point or refer to a cv-qualified object, but it is treated as if it does; a const-qualified access path cannot be used to modify an object even if the object referenced is a non-const object and can be modified through some other access path . [ Note: Cv-qualifiers are supported by the type system so that they cannot be subverted without casting (5.2.11). —end note ]

链接地址: http://www.djcxy.com/p/77594.html

上一篇: UIActivityViewController与NSURL音频文件只显示空投

下一篇: 捕获参考的稳定性