我用带有标志的 GCC 11.1.0 编译下面的代码-std=c++17。它发生在标准输出上打印initializer_list。
我用带有标志的 MSVC 编译了相同的代码,-std=c++17但它打印了“复制构造函数”。哪个编译器更符合cpp标准?编译器可以自由选择构造函数之一吗?
#include <iostream>
using namespace std;
struct S
{
S(int) { }
S(initializer_list<int>) { cout << "initializer_list"; }
S(const S&) { cout << "copy constructor"; }
operator int() const { return 1; };
};
int main()
{
S s1(20);
S s2{ s1 };
}
Run Code Online (Sandbox Code Playgroud) 我有一个简单的代码:
#include <atomic>
int main()
{
std::atomic<int> a = 0;
}
Run Code Online (Sandbox Code Playgroud)
这段代码可以在 GCC 11.1.0 和 -std=c++17 下正常编译,但在 -std=c++14 和 -std=c++11 时失败。
使用删除的函数 std::atomic::atomic(const std::atomic&)
这是为什么?在 C++17 类中std::atomic仍然没有复制构造函数。为什么此代码对 -std=c++17 有效?
当然,我知道首选样式是 use {},但我很好奇为什么上面的代码从 C++17 开始就可以很好地编译。
对于下面的代码,我们如何使用 std::forward 转发函数自动参数?
void push_value(std::vector<MyType>& vec, auto&& value)
{
vec.emplace_back(std::forward<?>(value));
}
Run Code Online (Sandbox Code Playgroud) 我有一个简单的功能:
void foo(atomic<int> a) { }
碰巧我可以foo()通过这种方式调用:foo({ });
但我不能以这种方式
调用:
foo(atomic<int>{ });由于错误消息copy constructor is a deleted function。我是用 C++14 编译的。
foo()可以用 C++17 编译 - 为什么?下面的代码无法编译:
template<typename... Ts>
void CreateArr(const Ts&... args)
{
auto arr[sizeof...(args) + 1]{ args... };
}
int main()
{
CreateArr(1, 2, 3);
}
Run Code Online (Sandbox Code Playgroud)
由于以下错误:
'arr':在直接列表初始化上下文中, for 的类型'auto [6]'只能从单个初始化表达式推导auto [6]':数组的元素类型不能包含'auto''const int'为'std::initializer_list<int>'我的问题是:
为什么我不能使用auto来定义数组的类型?
如何正确定义它以与模板一起使用?
std::string_view下面这段从到转换的代码怎么可能编译std::string:
struct S {
std::string str;
S(std::string_view str_view) : str{ str_view } { }
};
Run Code Online (Sandbox Code Playgroud)
但是这个不能编译?
void foo(std::string) { }
int main() {
std::string_view str_view{ "text" };
foo(str_view);
}
Run Code Online (Sandbox Code Playgroud)
第二个给出错误:cannot convert argument 1 from std::string_view to std::string和no sutiable user-defined conversion from std::string_view to std::string exists。
应该如何foo()正确打电话呢?
我想创建一个std::index_sequence包含给定数字的倍数的对象。
假设我想保存类似0, 3, 6, 9, ...or的值0, 2, 4, 6, 8, 10, ...。
如何创建这样的自定义序列?
我想通过给出要生成的值的数量并在连续值之间步进来使用它。
c++ ×7
c++17 ×6
auto ×2
templates ×2
atomic ×1
c++11 ×1
constructor ×1
copy-elision ×1
forward ×1
function ×1
parameters ×1
stdatomic ×1
string ×1
string-view ×1