这个代码在ISO C++中合法吗

Is this code legal in ISO C++?

本文关键字:C++ ISO 代码      更新时间:2023-10-16

所以我正在尝试实现可以取消初始化的函数参数。这是我写的代码。我的问题是,根据ISO C++标准(如果可能的话,版本14),它是否合法。

#include <iostream>
#include <typeinfo>
using namespace std;
template<typename type>
struct nzeroinittmpliteral
{
    nzeroinittmpliteral() { }    
    nzeroinittmpliteral(type arg) { d = arg; }    
    //nzeroinittmpliteral(const nzeroinittmpliteral &) = delete;    
    operator type () & { return d; }   
    operator type () && { return d; }  
    type d;
} ;
void func(bool bIsPointerValid, nzeroinittmpliteral<int *> pVar = {})
{
    if(bIsPointerValid)
    {
        cout << *pVar << endl;
    }
    else
    {
        pVar = new int;    
        *pVar = 8;    
        cout << *pVar << endl;    
        delete pVar;
    }
}
int main()
{
    func(true, { (int *)&(const int &)int{9} } );    
    func(false);
}

如果您想传递一个可能未初始化的参数,请不要传递,而是使用重载。外观:

void func(int value)
{
    cout << value << endl;
}
void func()
{
    // no 'value' was initialized here :)
    func(8);
}

或者,如果你想在体内提供一个默认值,只需给参数一个默认的值:

void func(int value = 8)
{
    cout << value << endl;
}

除此之外,您还可以查看boost::optional:

void func(boost::optional<int> optvalue = boost::none) {
    if (optvalue) {
        cout << *optvalue << endl;
    } else {
        // nothing passed
        cout << "foo" << endl;
    }
}

直接回答您的问题:您的代码是有效的。

func(true, { (int *)&(const int &)int{9} } );

通过将临时强制转换为const引用,可以将其生存期扩展到引用本身的生存期,该生存期在func返回后结束。但这太多余了,你可以简单地写:

void func(int* value) { if (value) {...} }
func(&(const int &)9);
func(nullptr);

传递的实际参数是nzeroinittmpliteral,它是通过始终调用其中一个构造函数来初始化的。默认构造函数不会初始化d成员,但这并没有太大的改进,因为它只是一个指针。使用nullptr更好,并且不需要布尔参数。