我想知道在这个代码中for (auto& i : v),for (auto&& i : v)在基于范围的for循环之间有什么区别:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = {0, 1, 2, 3, 4, 5};
std::cout << "Initial values: ";
for (auto i : v) // Prints the initial values
std::cout << i << ' ';
std::cout << '\n';
for (auto i : v) // Doesn't modify v because i is a copy of each value
std::cout << ++i << ' ';
std::cout << '\n';
for …Run Code Online (Sandbox Code Playgroud) 下面的代码
#include <optional>
#include <string>
#include <variant>
constexpr bool USE_VARIANT = 1;
using T = std::conditional_t<USE_VARIANT, std::variant<std::string>, std::string>;
struct S
{
T t;
};
constexpr int func()
{
S s{"str"};
return 0;
}
constexpr int x = func();
int main()
{
}
Run Code Online (Sandbox Code Playgroud)
无法使用 GCC trunk(编译器资源管理器链接)进行编译,并显示以下消息
In file included from <source>:4:
<source>:21:23: in 'constexpr' expansion of 'func()'
<source>:19:1: in 'constexpr' expansion of '(& s)->S::~S()'
<source>:10:8: in 'constexpr' expansion of '((S*)this)->S::t.std::variant<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >::~variant()'
/opt/compiler-explorer/gcc-trunk-20211231/include/c++/12.0.0/variant:1408:28: in 'constexpr' expansion of '((std::variant<std::__cxx11::basic_string<char, …Run Code Online (Sandbox Code Playgroud) 根据这个答案,我可以检查数组是否是索引的或关联的,如下所示:
$ declare -a a
$ declare -A b
$ echo ${a@a}
a
$ echo ${b@a}
A
Run Code Online (Sandbox Code Playgroud)
然而,如果我使用间接扩展,它就不起作用:
$ var=a
$ echo ${!var@a}
$ var=b
$ echo ${!var@a}
$
Run Code Online (Sandbox Code Playgroud)
然而,如果我初始化数组,它现在又可以工作了:
$ a=()
$ b=()
$ var=a
$ echo ${!var@a}
a
$ var=b
$ echo ${!var@a}
A
$
Run Code Online (Sandbox Code Playgroud)
这是预期行为还是 Bash 错误?
$ bash --version
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)
[...]
Run Code Online (Sandbox Code Playgroud) 注意:这是这个类似问题的变体,但具有可移动对象和显式声明的析构函数。
下面的代码
#include <functional>
#include <memory>
struct S
{
~S();
std::unique_ptr<int> x;
};
std::function<void(S)> x = [](S){};
Run Code Online (Sandbox Code Playgroud)
编译失败:
<source>:11:28: error: conversion from '<lambda(S)>' to non-scalar type 'std::function<void(S)>' requested
11 | std::function<void(S)> x = [](S){};
|
Run Code Online (Sandbox Code Playgroud)
如果我执行以下任一操作,它会按预期编译:
x成员变量;const S&而不是S.为什么会这样?为什么明确声明很~S重要?
c++ ×3
bash ×1
c++20 ×1
constexpr ×1
for-loop ×1
gcc ×1
indirection ×1
reference ×1
std-variant ×1
stl ×1