当我将函数作为参数传递给c ++中的其他函数时,我是否必须将其指定为
void callOtherFunctions(void f());
Run Code Online (Sandbox Code Playgroud)
要么
void callOtherFunctions(void (*f)());
Run Code Online (Sandbox Code Playgroud)
我不知道底层会发生什么,所以我尝试使用如下的简单程序运行两个版本,替换第二次运行所需的部分.
#include <iostream>
using namespace std;
void printHello();
void callOtherFunctions(void f());
int main() {
callOtherFunctions(printHello);
return 0;
}
void printHello(){
std::cout<<"\n Hello World";
}
void callOtherFunctions(void f()){
for (int i=0;i<5;++i){
f();
}
}
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,两者都执行相同的输出而没有警告.那么这是首选的方式,还是正确的方式(如果我做错了什么的话).在每种情况下实际发生的事情,当我传递指针时 - 它是否在那里执行地址函数,当我传递函数时 - 是否在那里复制整个函数?或者是其他东西?
考虑以下代码示例:
#include<iostream>
#include<vector>
#include<typeinfo>
int main(){
std::vector<int> v = {1 ,2,4};
for(auto &i:v) std::cout<<typeid(i).name();
for(auto k = v.begin(); k!=v.end();++k) std::cout<<typeid(k).name();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第一个循环代表基于范围的for循环,第二个循环代表带有迭代器的常规循环。我经常使用常规的,并且根据我的经验,它auto k
是迭代器的类型,而基于范围的循环的类型auto i
是int。上面程序的输出是:
i
和 N9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEE
这是基于范围的for循环的正常行为吗?因为像我这样的人会认为基于范围的for循环只是常规for循环的简写。
我有一个由 a 保护的资源类std::mutex
,其中访问它的任何方法都必须被锁定并且只能由单个线程执行。如果单独调用各个方法,这效果很好,但现在我需要将这些方法批处理在一起。在这种情况下,互斥锁只需锁定一次,并且这些方法不得再次锁定该互斥锁(否则将导致死锁)。
class Resource {
mutable std::mutex mtx;
int value = 10;
void handleOpStart() const {/* Activate batch mode */ std::cout << "HandleOp activate!"<< std::endl; }
void handleOpEnd() const {/* Deactivate batch mode */ std::cout << "HandleOp deactivate!"<< std::endl; }
public:
int read() const {
std::lock_guard<std::mutex> lock(mtx);
handleOpStart(); auto result = value + 10; handleOpEnd();
return result;
}
void write(int val) {
std::lock_guard<std::mutex> lock(mtx);
handleOpStart(); value = val; handleOpEnd();
}
template<typename Fn>
void batch(Fn fn) {
std::lock_guard<std::mutex> …
Run Code Online (Sandbox Code Playgroud) 我正在阅读Mozilla的C++可移植性指南,其中一条建议指出:
不要将初始化程序列表与对象一起使用
不可移植的示例(至少,这曾经是非便携式的,因为HP-UX!):
SubtlePoint myPoint = {300, 400};
在这一点上,这更像是一种风格,但为什么不挥霍并让自己成为一个好的构造函数呢?
我对这一行非常好奇" 不可移植的例子(至少,这曾经是非便携式的,因为HP-UX!) ".为什么初始化程序列表是不可移植的,在什么意义上?他们现在可以安全使用吗?又是什么术语HP-UX是指?