空指针指向大小为零的结构(空)...这是一个好习惯吗?

Pro*_*ter 1 c++ templates

我有一些null结构,例如:

struct null_type
{
    null_type& someNonVirtualMethod()
    {
        return *this;
    }
};
Run Code Online (Sandbox Code Playgroud)

在某些功能中,我需要传递对此类型的引用.原因:

template <typename T1 = null_type, typename T2 = null_type, ... >
class LooksLikeATupleButItsNotATuple
{
public:
    LooksLikeATupleButItsNotATuple(T1& ref1 = defParamHere, T2& ref2 = andHere..) 
        : _ref1(ref1), _ref2(ref2), ...
    {
    }

    void someCompositeFunctionHere()
    {
        _ref1.someNonVirtualMethod();
        _ref2.someNonVirtualMethod();
        ...
    }

private:
    T1& _ref1; 
    T2& _ref2; 
    ...;
};
Run Code Online (Sandbox Code Playgroud)

使用空引用作为默认参数是一个好习惯吗?:

*static_cast<NullType*>(0)
Run Code Online (Sandbox Code Playgroud)

它适用于MSVC,但我有些疑惑......

AnT*_*AnT 7

任何尝试在未定义的行为中创建空引用结果.因此,即使它似乎"有效",它也绝不是一种好的做法.

如果确实需要为引用类型的默认参数保留值,请声明相应类型的"虚拟"对象,并将其用作引用的默认值.