假设我们有模块接口源文件 foo.ixx,其中定义了模块 foo。我们用
import foo;
Run Code Online (Sandbox Code Playgroud)
在许多不同的 cpp 文件中。与传统头文件 foo.h 包含在许多不同的 cpp 文件中的情况相比,编译时间会减少吗?如果编译时间减少了,为什么会这样?
请考虑以下代码:
#include <iostream>
struct A{ // with implicit default constructor
int number;
};
struct B{
int number;
B(){}; // user-provided default constructor
};
int main()
{
A aa = {};
B bb = {};
std::cout << "aa.number: " << aa.number << std::endl;
std::cout << "bb.number: " << bb.number << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
在线运行代码会 产生以下输出:
aa.number: 0
bb.number: 19715
Run Code Online (Sandbox Code Playgroud)
为什么 bb.number 未初始化?我认为使用 ={} 可以保证零初始化?
这是一个如何设置当前#pragma包的示例:
#pragma pack(4)
Run Code Online (Sandbox Code Playgroud)
如何显示当前的#pragma pack设置?
请考虑以下代码:
int f(int i){return i*i;};
int main() {
void* p = static_cast<void*>(&f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
正如您在此处看到的,代码无法编译。为什么在 C++ 中不允许static_cast从int (*)(int)到void*?
有一个std::iteratorfor似乎很自然std::tuple。但是它没有实现,所以程序员实现了自己的版本。例如,可以在Jonathan Müller 的博客中找到。
我忽略了什么吗?tuple_iterator 没有“官方版本”有什么原因吗?
请考虑以下代码片段:
#include <iostream>
template <typename T>
class SaveType {
public:
T* allocate() const { return new T; }
T* cast(void* obj) const { return static_cast<T*>(obj); }
};
int main() {
int i = 4;
// "save" the type of the object i in SType:
SaveType<decltype(i)> SType;
// do type erasure
void* z = static_cast<void*>(&i);
// do stuff with z ...
// undo type erasure only with the help of SType
decltype(SType.allocate()) h = SType.cast(z);
std::cout << *h << std::endl;
} …Run Code Online (Sandbox Code Playgroud) 让函数 foo 带有以下“签名”:
template<typename ...Ts>
void foo(Ts ...args)
Run Code Online (Sandbox Code Playgroud)
这有点过头了,因为我只需要 foo 来处理doubles。如何修改 foo 使其double仅接受s ?
#include <tuple>
#include <iostream>
template<typename ...Ts>
void foo(Ts ...args)
{
std::tuple<Ts...> tu(args...);
std::apply([](Ts const&... tupleArgs)
{
((std::cout << tupleArgs << " "), ...);
}, tu);
}
int main()
{
foo(-2.44, -5.66, 78.99);
}
Run Code Online (Sandbox Code Playgroud)
输出如下:
-2.44 -5.66 78.99
在我看来,它new和它的对应物delete已经过时了,因为有智能指针和函数std::make_sharedand std::make_unique。真的吗?
我正在考虑关于我们内部 C++ 代码风格指南的公司内部注释的潜力。这是笔记的初稿:
“不想static_cast过dynamic_cast。dynamic_cast仅当动态(=运行时)类层次结构导航不可避免时才使用。“
我对这篇笔记的想法是:static_cast应该使用编译时检查的优势。在我看来,将潜在错误从运行时重新定位到编译时是个好主意。笔记的第二句是从这里复制和修改的:
我关于 C++ 编码风格的说明是否正确?