所以我正在尝试实现可以未初始化的函数参数。这是我写的代码。我的问题是它是否符合 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/