小编Ern*_*son的帖子

为什么 C++ 标准中 (void*)p 而不是 static_cast<void*>(p) ?

ISO/IEC 14882:2020
22.2.1.16 注 8:分配器中的默认构造将调用::new ((void*)p) T(args),但专用分配器可以选择不同的定义。

请您告诉我是否有任何原因不可以::new (static_cast<void*>(p)) T(args)

c++ static-cast

9
推荐指数
0
解决办法
250
查看次数

C++23 悬空引用编译错误

以下显然会导致 C++23 中的编译错误:

int& f(int& x) {
    int y = ++x;
    return y;
}
Run Code Online (Sandbox Code Playgroud)

错误cannot bind non-const lvalue reference of type 'int&' to an rvalue of type 'int'

但这似乎没有给我们一个警告:

int& f(int x) {
    int &y = ++x;
    return y;
}
Run Code Online (Sandbox Code Playgroud)

这在编译阶段是不是更难捕捉?

谢谢。

c++ reference c++23

2
推荐指数
1
解决办法
176
查看次数

使用 C 风格函数优化小型 std::string 通常毫无意义吗?

假设我们有以下代码,并且我们决定对其进行一些优化:

/// BM_NormalString
bool value = false;       
std::string str;
str = "orthogonal";
if (str == "orthogonal") {
    value = true;
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我们已经提出了两个非常简单明了的策略:

/// BM_charString
bool value = false;
char *str = new char[11];
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
    value = true;
}
delete[] str;
Run Code Online (Sandbox Code Playgroud)
/// BM_charStringMalloc
bool value = false;
char *str = (char *) std::malloc(11);
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
    value = true;
}
free(str);
Run Code Online (Sandbox Code Playgroud)

如果我们尝试对三种方法进行基准测试,令人惊讶的是,我们不会看到太大的差异。尽管在本地进行基准测试给了我更令人惊讶的令人不安的结果:

|      Benchmark       |     Time         | …
Run Code Online (Sandbox Code Playgroud)

c++ string malloc char

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

标签 统计

c++ ×3

c++23 ×1

char ×1

malloc ×1

reference ×1

static-cast ×1

string ×1