我经常看到有经验的程序员写!!x,即使预期的表达式是布尔值(即零或非零)而不是整数。
例如,来自 boost 的一行:
BOOST_ASSERT(!!p); // where `p` is a pointer
Run Code Online (Sandbox Code Playgroud)
什么!!p时候才p做呢?
我对布尔参数的理解是将表达式转换为整数类型的值,并将该值与零、显式或隐式(使用if或其三元运算符等效)进行比较。
因此,如果我对 Boolean 的理解是正确的,那么任何需要 Boolean 并且只期望0或被1错误实现的东西。
澄清一下:很明显,!转换为bool; 问题是明确询问为什么。
以下代码看似合理,但不适用于两大编译器
#include <type_traits>
template<template<class> class Tmp>
struct S{
template<class T>
using tmp_t = Tmp<T>;
static_assert(std::is_same_v< S<tmp_t>, S<Tmp> >,
"Not same?? How come?");
};
template<class> struct Dummy{};
template struct S<Dummy>;
Run Code Online (Sandbox Code Playgroud)
从7.1开始的gcc编译正常(https://godbolt.org/z/DjAcgP)
clang ( https://godbolt.org/z/ewBbZJ )
和
msvc ( https://godbolt.org/z/6ZmQwj )
没有这样做
这个代码标准符合吗?
考虑以下代码:
struct S{
int a, b;
S() : a(0), b(10) {}
};
S operator + (const S& v, int n){
S r = v;
r.a += n;
return r;
}
S operator - (const S& v, int n){
S r = v;
r.b -= n;
return r;
}
S v = S() + 1 - 1;
Run Code Online (Sandbox Code Playgroud)
是否有可能S() + 1 - 1将优化为S()?
编译器如何确定何时可以优化此类事情?
意思是,拥有类似于每个存储库部分的内容[repo_url]来覆盖全局(不适用于特定存储库)选项。
[core]
filemode = false
editor = notepad
[repo "example.com/repo1.git"]
[core]
filemode = true
# editor = notepad
[repo "example.com/repo2.git"]
[core]
editor = vim
# filemode = false
Run Code Online (Sandbox Code Playgroud)
在git中可以吗?
注意:我正在制作很多git clone存储库的克隆(),我将在这样的全局配置中指定它们
我希望我能更明确,但是有很多可能的场景在飞行中有几个例外——都涉及析构函数,但仍然如此。
从 C++98 到 C++17 的行为有何不同?
我敢于预言“飞行中有几个例外,没有办法抓住”。
擦除第一个迭代器在最后一个迭代器之后的范围时会发生什么?
std::vector<int> v{1,2};
v.erase(
v.begin() + 1,
v.begin()
);
Run Code Online (Sandbox Code Playgroud)
其他容器呢?
以时间为例:如果我们有开始时间和结束时间,找到它们之间的小时数的最佳方法是什么?
如果我们采用 12 小时制,我们会得到以下结果
最有效的方法是什么?