下面的代码:
struct non_trivially {
non_trivially() {};
};
union U {
bool dummy{false};
non_trivially value;
};
int main() {
U tmp;
}
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/1cMsqq9ee
在 clang (13.0.0) 上产生下一个编译器错误:
source>:11:7: error: call to implicitly-deleted default constructor of 'U'
U tmp;
^ <source>:7:19: note: default constructor of 'U' is implicitly deleted because variant field 'value' has a non-trivial default constructor
non_trivially value;
Run Code Online (Sandbox Code Playgroud)
但使用 MSVC (19.30) 成功编译。
根据 cppreference 它应该是一个有效的代码:https ://en.cppreference.com/w/cpp/language/union
如果联合体包含具有非平凡默认构造函数的非静态数据成员,则默认情况下将删除联合体的默认构造函数,除非联合体的变体成员具有默认成员初始值设定项。
在我的示例中,U 中有一个带有默认成员初始值设定项的替代方案,因此不应删除默认构造函数,但确实如此。我缺少什么?
类型特征是否应该能够处理诸如std::vector < std::unique_ptr <int> >
并且检测到它不是可复制构造的情况?
以下是https://ideone.com/gbcRUa(运行g ++ 4.8.1)的示例
#include <type_traits>
#include <vector>
#include <iostream>
#include <memory>
int main()
{
// This prints 1, implying that it's copy constructible, when it's clearly not
std::cout << std::is_copy_constructible< std::vector<std::unique_ptr<int> > >::value << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果这是正确的行为is_copy_constructible
,有没有办法检测复制结构是否形成错误?好吧,除了让它无法编译之外.
已经有关于一些问题的今天std::weak_ptr
和std::owner_less
及其关联容器使用std::set
和std::map
.有很多帖子声明weak_ptr
在a 中使用a std::set
是不正确的,因为如果弱指针到期,它将是Undefined Behavior.它是否正确?