实施安全的nullptr [英] implementation safe nullptr

查看:93
本文介绍了实施安全的nullptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的代码在旧版C ++(使用"NULL"的C ++代码)和新C ++ 11标准(使用"nullptr"的C ++代码)上均可编译

I'd like to keep my code compilable both on legacy C++ (C++ code using "NULL") and new C++11 standard (C++ code using "nullptr")

我正在使用GCC,但计划在我完成最重要的事情时也为VS重新编译整个代码库.

I'm using GCC, but planning to recompile the whole codebase also for VS when I'll finish most important things.

我希望GCC和VS都能做到类似的事情

Should I expect both GCC and VS will do something like

#define NULL nullptr

还是更好的办法是我自己做(当然使用一个不同的名称,其中MY_LIB将由我的库后缀替换)?

Or Is better I'll do that myself (using of course a different name, where MY_LIB will be replaced by my library suffix)?

#ifndef nullptr
    #define MY_LIB_NULL NULL
#else
    #define MY_LIB_NULL nullptr
#endif

我想实现的是无论是否实现了C ++ 11的所有功能都可以编译的代码(并且由于我没有使用模板,所以很少.)

What I want to achieve is code that compiles regardless of wich C++11 features have been implemented or not (and since i'm not using templates, there are very few of them).

例如,关键字"override"和"final"已经完成.

For example the keywords "override" and "final" are already done.

MY_LIB_OVERRIDE //macro, defines to "override" if c++11 is present.
MY_LIB_FINAL    //macro, defines to "final" if c++11 is present.

我问这个问题是因为我知道"nullptr"问题有点奇怪,所以也许只是做我已经为覆盖和最终做过的事情是错误的.需要对此的意见.任何帮助都很好.

I'm asking the question because I know the "nullptr" question is a bit strange, so maybe just doing the same I already did for override and final, is wrong. Needs opinions about that. Any help is wellcome.

推荐答案

您可能可以通过以下方式创建类型为my_nullptr_t的"false" my_nullptr:

You could probably create a "false" my_nullptr of type my_nullptr_t the following way:

const class my_nullptr_t
{
    public:

        /* Return 0 for any class pointer */
        template<typename T>
        operator T*() const
        {
            return 0;
        }

        /* Return 0 for any member pointer */
        template<typename T, typename U>
        operator T U::*() const
        {
            return 0;
        }

        /* Safe boolean conversion */
        operator void*() const
        {
            return 0;
        }

    private:

        /* Not allowed to get the address */
        void operator&() const;

} my_nullptr = {};

这可与C ++ 03和C ++ 11一起使用,并且无论采用哪种C ++ 11功能,都应始终安全.该解决方案实际上已经在本主题中进行了讨论,该提议基于

This works with C++03 and C++11 and should always be safe, whichever C++11 features are implemented. That solution was actually already discussed in this topic that proposed a version of nullptr_t based on the Official proposal.

这篇关于实施安全的nullptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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