我有这些课程:
#include <type_traits>
template <typename T>
class A {
public:
static_assert(std::is_default_constructible_v<T>);
};
struct B {
struct C {
int i = 0;
};
A<C> a_m;
};
int main() {
A<B::C> a;
}
Run Code Online (Sandbox Code Playgroud)
编译时,a_m不是默认可构造的,而是a可构造的。
更改C为:
struct C {
int i;
};
Run Code Online (Sandbox Code Playgroud)
一切安好。
使用 Clang 9.0.0 测试。
我尝试使用三个编译器(msvc2017,gcc8.2,clang7.0)的下一个代码,msvc2017一直工作,但gcc和clang没有.我想了解我的代码有什么问题,以及为什么编译器无法编译它.
#include <cassert>
#include <iostream>
#include <cstdlib>
class Downloader
{
public:
struct Hints
{
int32_t numOfMaxEasyHandles = 8;
//Hints(){} // <= if I uncomment this all works gcc+clang+msvc
//Hints() = default; // <= if I uncomment this neither clang no gcc works (msvc - works)
};
static Downloader *Create(const Hints &hints = Hints());
};
Downloader* Downloader::Create(const Hints &hints)
{
std::cout << hints.numOfMaxEasyHandles << std::endl;
return nullptr;
}
int main()
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以在https://wandbox.org/上自行使用此代码,并查看错误:
prog.cc:16:58: error: …Run Code Online (Sandbox Code Playgroud) 我有一个类 C,其中包含一个 struct S 和一个 std::variant 作为成员。struct S 有一个 int 成员 a,初始化为 0。代码如下:
#include <variant>
class C
{
struct S {
int a = 0;
};
std::variant<S> test;
};
int main()
{
C ctest;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 gcc 12.2.1(也使用不同的编译器)编译此代码时,出现以下错误:
#include <variant>
class C
{
struct S {
int a = 0;
};
std::variant<S> test;
};
int main()
{
C ctest;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看代码和错误消息: https: //onlinegdb.com/ZdfGp9avn
但是,如果我从结构 S 中删除默认赋值 =0,则代码编译时不会出现错误。为什么会发生这种情况?如何在不删除默认分配的情况下修复此错误?在这种情况下,有默认分配与没有默认分配有什么区别?
考虑以下代码:
#include <type_traits>
struct outer {
struct inner {
unsigned int x = 0;
};
// static_assert(std::is_default_constructible<inner>::value,
// "not default ctorable - inside");
};
static_assert(std::is_default_constructible<outer::inner>::value,
"not default ctorable - outside");
Run Code Online (Sandbox Code Playgroud)
这编译得很好。但是 - 如果我取消注释内部的静态断言outer- 两个断言都会因 clang++ 和 gcc++ 失败。为什么他们不能都通过?
笔记:
inner事实上,在第一个静态断言的点上,这个类是完整的。断言不会因不完整而失败(失败会产生关于不完整的特定错误消息)。
与相关的为什么我的类不可默认构造不同?,这里 - 没有模板,所以没有定义前的实例化。
如果删除 的初始化程序x并启用断言,则代码会编译。(这也不同于相关问题。)
这个:
#include <type_traits>
struct outer {
struct inner {
unsigned int x = 0;
};
inner get_an_inner() {
static_assert(std::is_default_constructible<outer::inner>::value,
"not default ctorable - outside");
return inner{}; …Run Code Online (Sandbox Code Playgroud)