当前位置:网站首页>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
}
边栏推荐
- 2022安全员-C证考试题及模拟考试
- If you want to rewind the video picture, what simple methods can you use?
- C return multiple values getter setter queries the database and adds the list return value to the window
- QT实现界面跳转
- [reading notes] programmer training manual - practical learning is the most effective (project driven)
- C # use system data. The split mixed mode assembly is generated for the "v2.0.50727" version of the runtime, and it cannot be loaded in the 4.0 runtime without configuring other information
- Connected block template and variants (4 questions in total)
- AcWing 245. Can you answer these questions (line segment tree)
- 【读书笔记】程序员修炼手册—实战式学习最有效(项目驱动)
- What is the difference between an intermediate human resource manager and an intermediate economist (human resources direction)?
猜你喜欢
[opencv] - comprehensive examples of five image filters
LFM信号加噪、时频分析、滤波
CoordinatorLayout + TabLayout + ViewPager2(里面再嵌套一个RecyclerView),RecyclerView的滑动冲突解决
Coordinatorlayout + tablayout + viewpager2 (there is another recyclerview nested inside), and the sliding conflict of recyclerview is solved
Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market
MySQL operates the database through the CMD command line, and the image cannot be found during the real machine debugging of fluent
An analysis of circuit for quick understanding
What kind of good and cost-effective Bluetooth sports headset to buy
Deployment practice and problem solving of dash application development environment based on jupyter Lab
Infix expression to suffix expression (computer) code
随机推荐
Pychart creates new projects & loads faster & fonts larger & changes appearance
Comparative analysis of MVC, MVP and MVVM, source code analysis
[road of system analyst] collection of wrong topics in enterprise informatization chapter
【带你学c带你飞】2day 第8章 指针(练习8.1 密码开锁)
The basic steps of using information theory to deal with scientific problems are
How to turn off the LED light of Rog motherboard
pytest 测试框架
Websocket + spingboot realize code scanning login
Basic 01: print string
The middle element and the rightmost element of the shutter
Stack - es - official documents - filter search results
批量检测url是否存在cdn—高准确率
【无标题】
How to run oddish successfully from 0?
Bash bounce shell encoding
A quick understanding of digital electricity
Remote connection to MySQL under windows and Linux system
[learn C and fly] 1day Chapter 2 (exercise 2.2 find the temperature of Fahrenheit corresponding to 100 ° f)
flutter 中間一個元素,最右邊一個元素
CVPR 2022 | 大连理工提出自校准照明框架,用于现实场景的微光图像增强