这个代码在ISO C++中合法吗
Is this code legal in ISO C++?
所以我正在尝试实现可以取消初始化的函数参数。这是我写的代码。我的问题是,根据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
更好,并且不需要布尔参数。
相关文章:
- 如何使用 C++将 ISO-2022-KR 编码转换为 UTF-8 编码?
- ISO C++禁止声明没有类型的"setInputNombre"
- ISO C++禁止指针和整数 [-fpermissive] [c++] 之间的比较
- 为什么我会收到此警告:ISO c++ 禁止可变长度数组"v"[-Wvla]
- ISO 中禁止可变长度数组 C++崇高文本中的错误 3.
- 是否存在经过认证(ISO 26262或类似)C++标准库?
- 张量流错误 此文件需要编译器和库支持 ISO C++ 2011 标准
- 错误:ISO C++禁止可变长度数组"subVec"[-Werror=vla]
- Clang-CL 警告 strnicmp 已弃用,请使用 ISO C 并C++符合标准的名称_strnicmp
- Qt 错误 iso c++ 禁止指针和整数之间的比较 -permissive
- DEV C++ 第 69 行 [错误] ISO "for" 范围更改了"i"的名称查找 [-允许]
- 错误:ISO C++禁止在指针和整数 [-fallowive] 之间进行比较
- 警告:ISO C++禁止可变长度数组
- 包括C++标题,"..."与<...>风格,ISO / IEC官方意见?
- 在 c++ 中将 ISO 日期时间转换为本地日期时间并提取时间
- 在 Boost 中解析 RFC3339/ISO 8601 时间戳
- :<command-line>0:3:警告:ISO C++11 要求宏名称后有空格
- C++错误:ISO C++禁止声明.没有类型
- 警告:ISO C++禁止将字符串常量转换为'char*' [-Wwrite-strings]
- 将 OR 放入 if 语句会导致 ISO C++禁止指针和整数之间的比较(f 允许)