小编Dav*_*e S的帖子

Union的默认构造函数被隐式删除

下面的代码:

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 中有一个带有默认成员初始值设定项的替代方案,因此不应删除默认构造函数,但确实如此。我缺少什么?

c++ language-lawyer

27
推荐指数
2
解决办法
6397
查看次数

问题与is_copy_constructible

类型特征是否应该能够处理诸如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,有没有办法检测复制结构是否形成错误?好吧,除了让它无法编译之外.

c++ type-traits c++11 g++4.8

14
推荐指数
1
解决办法
1265
查看次数

在std :: set或std :: map的键中使用weak_ptr是否安全

已经有关于一些问题的今天std::weak_ptrstd::owner_less及其关联容器使用std::setstd::map.有很多帖子声明weak_ptr在a 中使用a std::set是不正确的,因为如果弱指针到期,它将是Undefined Behavior.它是否正确?

c++ weak-ptr c++11

7
推荐指数
1
解决办法
2456
查看次数

标签 统计

c++ ×3

c++11 ×2

g++4.8 ×1

language-lawyer ×1

type-traits ×1

weak-ptr ×1