什么是`const_cast`的效果,当" const-ness"不需要?

时间:2017-01-19 06:28:58

标签: c++ language-lawyer const-cast well-formed

const_cast用于移除或添加" const-ness"一个物体 然而,这种演员的效果或行为是什么,它不会改变" const-ness"?

换句话说,如果const_cast<Class&>(object)应用于已经为非常量object类型的Class,会发生什么情况。
同样,如果const_cast<const Class&>(object)应用于已object类型的const Class,会发生什么。

虽然我认为它应该被很好地定义,但仍然想确认它。特别是如果标准中有任何权威参考或某些内容。

用例:在模板化代码中,有时为避免额外代码,我们可能希望const_cast每个对象都会出现问题。它可以与const或非const对象一起传递。 e.g。

struct X {
  void foo ();
};

template<typename T>
void call_foo (T& t)  // `T` is either `X` or `const X` (& possibly children of `X`)
{
  X& x = const_cast<X&>(t);
  x.foo();
}

假设我们暂时不担心volatile说明符。

2 个答案:

答案 0 :(得分:4)

完全没问题。没有效果 - 好像你根本没有public static void main(String[] args) { try { URL url = new URL ("https://.../......"); String encoding = Base64.getEncoder().encodeToString(("login:password").getBytes()); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setRequestProperty ("Authorization", "Basic " + encoding); InputStream content = (InputStream)connection.getInputStream(); BufferedReader in = new BufferedReader (new InputStreamReader (content)); String line; while ((line = in.readLine()) != null) { System.out.println(line); } } catch(Exception e) { e.printStackTrace(); } }

请注意,您可以使用std::is_const检查特定类型是否为const。但如果做到这一点的唯一理由是避免无操作const_cast,我就不会打扰。

答案 1 :(得分:1)

如果某个对象不是const,则使用const_cast<>删除const不会产生任何影响。从逻辑上来说,从已经缺少该属性的东西中删除属性什么都不做。

例外情况是对象也是易失性的,例如;

 volatile SomeType x;   // const qualifier may also be used here

 SomeType &something = const_cast<SomeType &>(x);

也会移除volatile限定符,x是否为const。任何使用某些东西访问x然后都会导致未定义的行为。

如果此示例更改为

 SomeType y;
 volatile SomeType& x(y);
 SomeType &something = const_cast<SomeType &>(x);

然后使用something是合法的(因为y不易变),但如果x用于以某种方式修改y,编译器可能会也可能不会确保在访问something时反映这些更改(反之亦然)。如果信号处理程序对x执行某些操作,那么验证代码是否按预期工作将非常具有挑战性。

对于您的使用案例,使用const_cast没有意义。重载函数很容易,因此需要const或非const引用。

  void func(Something &x);
  void func(const Something &x);

如果给出const对象,则会调用第二个。使用const_cast删除const ness对第一个没有影响。在第二种情况下,它可能允许更改不可更改的内容,因此可能导致未定义的行为(如果以这种方式使用非const引用)。

相关问题