当前位置:网站首页>Stdref and stdcref
Stdref and stdcref
2022-07-02 02:38:00 【heater404】
std::ref and std::cref
1 std::ref and std::cref
c++11 Introduction in std::ref Used to get a reference to a variable , This introduction is to solve some parameter transfer problems .
- std::ref Used to wrap values passed by reference .
- std::cref For packing according to const Value passed by reference .
We know C++ There are references in , why C++11 There is another one introduced in std::ref Well ? It's mainly about functional programming ( Such as std::bind) When use , It's a direct copy of the parameters , Not references .
#include <iostream>
#include <functional>
void f(int &n1, int &n2, const int &n3)
{
std::cout << "In function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
++n1; // increments the copy of n1 stored in the function object
++n2; // increments the main()'s n2
// ++n3; // compile error
}
int main(int, char **)
{
int n1 = 1, n2 = 2, n3 = 3;
std::function<void()> bound_f = std::bind(f, n1, std::ref(n2), std::cref(n3));
n1 = 10;
n2 = 11;
n3 = 12;
std::cout << "Before function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
bound_f();
std::cout << "After function: " << n1 << ' ' << n2 << ' ' << n3 << '\n';
}
Output :
Before function: 10 11 12
In function: 1 11 12
After function: 10 12 12
The above code is executing std::bind after , In function f() in n1 The value of is still 1,n2 and n3 Changed to the modified value , explain std::bind A copy of the parameter is used instead of a reference , Therefore, it must be shown that std::ref For reference binding . Why exactly std::bind Do not use references , There may indeed be some needs , bring C++11 Our designers believe that copy should be adopted by default , If the user has a demand , add std::ref that will do .
Allied , also std::thread It must also be explicitly passed std::ref To bind references and pass parameters , otherwise , The reference declaration of formal parameters is invalid .
void foo(string &msg)
{
msg = "i am foo string";
}
string msg = "hello world";
thread *th = new thread(foo, std::ref(msg));
th->join();
std::cout << "msg:" << msg << endl;
2 std::bind
Can be std::bind Function as a general function adapter , It takes a callable object , Generate a new callable object to fit the parameter list of the original object .std::bind Bind the callable object with its parameters , The result after binding can be used std::function preservation .
2.1 Bind ordinary functions
#include <functional>
void foo(string &msg, int i)
{
msg = "i am foo:" + msg + to_string(i);
}
int main(int, char **)
{
auto f = std::bind(foo, std::placeholders::_1, 100);
string msg;
f(std::ref(msg));
std::cout << msg << endl; // i am foo:100
}
You can bind parameters when Binding , You can also occupy a seat first , Pass in parameters when executing .
2.2 Bind a member function
typedef struct
{
/* data */
void foo(string &msg, int i)
{
msg = "i am foo:" + msg + to_string(i);
}
} bar;
int main(int, char **)
{
bar b;
auto f = std::bind(bar::foo, &b, std::placeholders::_1, 100);
string msg;
f(std::ref(msg));
std::cout << msg << endl; // i am foo:100
}
For member functions , When Binding :
- The specified method must be displayed bar::foo.
- You must know which object this method belongs to , So the second parameter is the address of the object &b
2.3 std::thread
In the use of std::thread When , We also need to pay attention to the same problem .
typedef struct
{
/* data */
void foo(string &msg, int i)
{
msg = "i am foo:" + msg + to_string(i);
}
} bar;
int main(int, char **)
{
string msg;
bar b;
thread th(bar::foo, &b, std::ref(msg), 100);
th.join();
std::cout << msg << endl; // i am foo:100
}
边栏推荐
- 离婚3年以发现尚未分割的共同财产,还可以要么
- How does proxy IP participate in the direct battle between web crawlers and anti crawlers
- [pit] how to understand "parameter fishing"
- Comparative analysis of MVC, MVP and MVVM, source code analysis
- Webgpu (I): basic concepts
- JS slow animation
- Open that kind of construction document
- Sword finger offer 31 Stack push in and pop-up sequence
- Which brand of sports headset is better? Bluetooth headset suitable for sports
- 使用开源项目【Banner】实现轮播图效果(带小圆点)
猜你喜欢
Software development life cycle -- waterfall model
Pychart creates new projects & loads faster & fonts larger & changes appearance
批量检测url是否存在cdn—高准确率
Face++ realizes face detection in the way of flow
STM32__ 05 - PWM controlled DC motor
[learn C and fly] 1day Chapter 2 (exercise 2.2 find the temperature of Fahrenheit corresponding to 100 ° f)
AR增强现实可应用的场景
The basic steps of using information theory to deal with scientific problems are
结婚后
Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
随机推荐
Batch detect whether there is CDN in URL - high accuracy
[untitled]
Connected block template and variants (4 questions in total)
Build a modern data architecture on the cloud with Amazon AppFlow, Amazon lake formation and Amazon redshift
STM32__ 05 - PWM controlled DC motor
Sword finger offer 42 Maximum sum of continuous subarrays
Basic 01: print string
STM32__05—PWM控制直流电机
批量检测url是否存在cdn—高准确率
[staff] pitch representation (treble clef | C3 60 ~ B3 71 pitch representation | C4 72 pitch representation | C5 84 pitch representation)
CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
LFM signal denoising, time-frequency analysis, filtering
Flutter un élément au milieu, l'élément le plus à droite
Vsocde has cli every time it is opened js
Is bone conduction earphone better than traditional earphones? The sound production principle of bone conduction earphones is popular science
STM32F103——两路PWM控制电机
[liuyubobobo play with leetcode algorithm interview] [00] Course Overview
QT implementation interface jump
Formatting logic of SAP ui5 currency amount display
[question 008: what is UV in unity?]