Posts

Showing posts with the label Ref

C++ Difference Between Std::ref(T) And T&?

Answer : Well ref constructs an object of the appropriate reference_wrapper type to hold a reference to an object. Which means when you apply: auto r = ref(x); This returns a reference_wrapper and not a direct reference to x (ie T& ). This reference_wrapper (ie r ) instead holds T& . A reference_wrapper is very useful when you want to emulate a reference of an object which can be copied (it is both copy-constructible and copy-assignable ). In C++, once you create a reference (say y ) to an object (say x ), then y and x share the same base address . Furthermore, y cannot refer to any other object. Also you cannot create an array of references ie code like this will throw an error: #include <iostream> using namespace std; int main() { int x=5, y=7, z=8; int& arr[] {x,y,z}; // error: declaration of 'arr' as array of references return 0; } However this is legal: #include <iostream> #include <functional> // ...