c++ - 这段代码在 ISO C++ 中合法吗?

标签 c++ initialization c++14 iso

所以我正在尝试实现可以​​未初始化的函数参数。这是我写的代码。我的问题是它是否符合 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 更好,并且不需要 bool 参数。

关于c++ - 这段代码在 ISO C++ 中合法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29198882/

相关文章:

java - 面试问题 - 在排序数组 X 中搜索索引 i 使得 X[i] = i

c++ - 可以(由编译器)使用多少线程来初始化全局对象(在函数 main 之前)

c - C中int指针的初始化

c++ - 仿函数基类的模糊重载

C++ 条件

c++ - 返回值优化和副作用

c++ - 自定义分配器泄漏内存

c - 将字符串初始化为 {0, } 有什么作用?

c++ - Lamda 仅在声明为 'auto' 时编译,而不是在声明为 'bool' 时编译

c++ - 为什么我们不能使函数显式化?