在入口处reinterpret_cast,cppref说:
可以将积分,枚举,指针或指向成员类型的表达式转换为其自己的类型.结果值与表达式的值相同.(自C++ 11以来)
但是,以下代码无法编译(clang 5.0 with -std=c++1z):
enum class A : int {};
int main()
{
A a{ 0 };
reinterpret_cast<int>(a); // error : reinterpret_cast from 'A' to 'int' is not allowed
}
Run Code Online (Sandbox Code Playgroud)
为什么不像reinterpret_castC++标准那样表现?
#include <range/v3/all.hpp>
#include <vector>
#include <string>
#include <deque>
using namespace std::literals;
int main()
{
auto src = std::vector{"123"s, "456"s, "789"s};
auto movable_rng = ranges::subrange(
std::make_move_iterator(src.begin()),
std::make_move_iterator(src.end()));
auto dst = ranges::to<std::deque<std::string>>(movable_rng);
for (auto e : src)
{
std::cout << e << std::endl;
}
for (auto e : dst)
{
std::cout << e << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
用 libc++ 用 clang 10 编译,输出为:
123
456
789
123
456
789
Run Code Online (Sandbox Code Playgroud)
正如我所料,结果应该是:
""
""
""
123
456
789
Run Code Online (Sandbox Code Playgroud)
为什么即使是迭代器,ranges-v3 也不移动元素 std::move_iterator?
========更新======
我的范围版本是: …
#include <limits>
#include <cstdint>
#include <iostream>
template<typename T>
T f(T const a = std::numeric_limits<T>::min(),
T const b = std::numeric_limits<T>::max())
{
if (a >= b)
{
throw 1;
}
auto n = static_cast<std::uint64_t>(b - a + 1);
if (0 == n)
{
n = 1;
}
return n;
}
int main()
{
std::cout << f<int>() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
g++-11 -std=c++20 -O2应该输出0比其他1!
clang++ 没问题。如果我-O2改为-O0,g++-11 也可以。
参见:在线演示
为什么 g++ -O2 包含一个错误而 -O0 可以?
给定一个包含字符串"Hello World"的文件(注意'Hello'和'World'之间有一个空格).
int main()
{
ofstream fout("test.txt");
fout.write("Hello World", 12);
fout.close();
ifstream fin("test.txt");
vector<string> coll((istream_iterator<string>(fin)),
(istream_iterator<string>()));
// coll contains two strings 'Hello' and 'World' rather than
// one string "Hello World" that is just I want.
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我希望istream中的字符串只能用'\n'而不是'','\n'等分隔.
我应该怎么做?
package main
import (
"fmt"
"time"
)
func main() {
n := 1024
dst1 := make([]byte, n)
dst2 := make([]byte, 0, n)
dst3 := make([]byte, 0, n)
start := time.Now()
for i := 0; i < n; i++ {
dst1[i] = byte(i)
}
fmt.Println(uint64(time.Since(start).Microseconds()))
start = time.Now()
for i := 0; i < n; i++ {
dst2 = append(dst2, dst1[i])
}
fmt.Println(uint64(time.Since(start).Microseconds()))
start = time.Now()
for i := 0; i < n; i++ {
dst3 = append(dst3, dst1...)
}
fmt.Println(uint64(time.Since(start).Microseconds())) …Run Code Online (Sandbox Code Playgroud) 我没能用VC++编译gcc的C++标准库,反之亦然.
为什么几乎所有的C++标准库都不可移植(包括clang,gcc和vc ++)?
我也尝试过STLport,但它太旧了,无法支持C++ 11.
我正在为嵌入式系统编写自己的mini-STL,由于其不可移植性,我无法使用编译器提供的STL.所以,我必须关心这一点.
是否有可移植C++标准库的实现?
c++ compiler-construction standards-compliance c++-standard-library c++11