C ++:*((SomeType *)0)? [英] C++: *((SomeType*) 0 )?

查看:265
本文介绍了C ++:*((SomeType *)0)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到过这种句法结构几次,我想知道:

I've come across this syntactic construct a few times, and I'm wondering:


  1. 这是做什么? li>
  2. 设计推理是什么?

它看起来像这样:

struct SubType : public SomeSuperType {

    SubType(int somthing) : SuperType(something), m_foo(*((FooType *)0))
    {}

    private:
    FooType m_foo;
}

要清楚,代码工作。但目的是什么? m_foo 的状态是什么?

To be clear, the code works. But what's the purpose? What would be the status of m_foo without that line?

推荐答案

这种结构的目的是在你正式需要一个对象,但不想要或不能声明一个真正的对象的情况下,模拟类型 SomeType 的假的未命名对象。

The purpose of this construct is to emulate a fake unnamed object of type SomeType in situations when you formally need an object, but don't want or can't declare a real one. It has its valid uses and does not necessarily cause undefined behavior.

一个典型的例子是确定某个类成员的大小

A classic example would be determining the size of some class member

sizeof (*(SomeClass *) 0).some_member


$ b b

或类似的应用程序decltype

or a similar application of decltype

decltype((*(SomeClass *) 0).some_member)

上述两个示例都不会导致任何未定义的行为。在非评估的上下文表达式如 *(SomeClass *)0 是完全合法和有效的。

Neither of the above examples causes any undefined behavior. In non-evaluated context expressions like *(SomeClass *) 0 are perfectly legal and valid.

看到这种技术用于语言标准本身的说明性目的,如8.3.5 / 12

You can also see this technique used for illustrative purposes in the language standard itself, as in 8.3.5/12


尾随返回类型是最对于在$ declare-id之前指定更复杂的
的类型有用:

A trailing-return-type is most useful for a type that would be more complicated to specify before the declarator-id:

template <class T, class U> auto add(T t, U u) -> decltype(t + u); 

而不是

template <class T, class U> decltype((*(T*)0) + (*(U*)0)) add(T t, U u);


观察 decltype 下使用表达式来执行二进制的结果类型的编译时预测,使用*)0)+(*(U *)0) T U 之间的 + 运算符。

Observe how the (*(T*)0) + (*(U*)0) expression is used under decltype to perform compile-time prediction of the result type of binary + operator between types T and U.

当然,这些技巧只有在非评估上下文中有效,如上所示。

Of course, again, such tricks are only valid when used in non-evaluated contexts, as shown above.

它用作null引用的初始化器,如在

Sometimes it is used as an initializer for "null references" as in

SomeType &r = *(SomeType *) 0;

但这实际上跨越了合法的边界并产生未定义的行为。

but this actually crosses the boundary of what's legal and produces undefined behavior.

在您的具体示例中有什么无效,因为它试图在计算上下文中访问无效的空值。

What you have in your specific example is invalid, since it attempts to access an invalid "null lvalue" in evaluated context.

PS在C语言中,还有规范的特殊部分,它说运算符& * 彼此抵消, & *(SomeType *)0 是有效的,并保证求值为空指针。但它不扩展到C ++。

P.S. In C language there's also that peculiar part of specification that says that operators & and * cancel each other, meaning that &*(SomeType *) 0 is valid and guaranteed to evaluate to null pointer. But it does not extend to C++.

这篇关于C ++:*((SomeType *)0)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆