Differrent function signatures C++ - c++

Found some C++ tests, one of a questions: what is diff between function signatures.
Am I right with following answers?
void f(data); // 1)calls copy constructor of data to pass in function
void f(data*); // 2)data passes to function by ptr, no copy constructor called
void f(data const*); // 3)same as 2, but not allowed to change pointer, allowed to change data
void f(data* const); // 4)same as 2, but not allowed to change data, allowed to change pointer
void f(data const* const); // 5) same as 2, niether ptr and data can be changed
void f(data&); // 6) same as 2, but ref instead of ptr
void f(data const&); // 7) same as 3
void f(data&&); // 8) Refence to reference(most subtle moment to me), move constructor, depends on function original data can be erased

Not quite:
Not necessarily copy. Other constructors can be used to initialise the parameter.
and 4. are wrong way 'round.
There is no such thing as "reference to a reference". That is an rvalue reference. No constructor is called when binding a reference to a value.

As an additional statement to 8: As already mentioned here, there is no such thing like a reference to a reference (at least not as a plain fundamental C++ object/value type category). Its exact reference type depends on the usage context, but in the most cases, it's called an rvalue reference. In a non-evaluated template argument context - f being a function template and date being a typed template argument - its reference type is called forwarding reference. To stay strictly in standard terminology, it's also not a universal reference as Coy Kramer stated here since the committee didn't accept the terminology of Scott Meyers in 2015 for this for various reasons.

Related

std::async no matching overloaded function found [duplicate]

I've noticed that it's impossible to pass a non-const reference as an argument to std::async.
#include <functional>
#include <future>
void foo(int& value) {}
int main() {
int value = 23;
std::async(foo, value);
}
My compiler (GCC 4.8.1) gives the following error for this example:
error: no type named ‘type’ in ‘class std::result_of<void (*(int))(int&)>’
But if I wrap the value passed to std::async in std::reference_wrapper, everything is OK. I assume this is because std::async takes it's arguments by value, but I still don't understand the reason for the error.
It's a deliberate design choice/trade-off.
First, it's not necessarily possible to find out whether the functionoid passed to async takes its arguments by reference or not. (If it's not a simple function but a function object, it could have an overloaded function call operator, for example.) So async cannot say, "Hey, let me just check what the target function wants, and I'll do the right thing."
So the design question is, does it take all arguments by reference if possible (i.e. if they're lvalues), or does it always make copies? Making copies is the safe choice here: a copy cannot become dangling, and a copy cannot exhibit race conditions (unless it's really weird). So that's the choice that was made: all arguments are copied by default.
But then, the mechanism is written so that it actually fails to then pass the arguments to a non-const lvalue reference parameter. That's another choice for safety: otherwise, the function that you would expect to modify your original lvalue instead modifies the copy, leading to bugs that are very hard to track down.
But what if you really, really want the non-const lvalue reference parameter? What if you promise to watch out for dangling references and race conditions? That's what std::ref is for. It's an explicit opt-in to the dangerous reference semantics. It's your way of saying, "I know what I'm doing here."
std::async (and other functions that do perfect forwarding) look at the type of the argument that you pass to figure out what to do. They do not look at how that argument will eventually be used. So, to pass an object by reference you need to tell std::async that you're using a reference. However, simply passing a reference won't do that. You have to use std::ref(value) to pass value by reference.
The issue itself is only marginally related to std::async(): When defining the result of the operation, std::async() uses std::result_of<...>::type with all its arguments being std::decay<...>::type'ed. This is reasonable because std::async() takes arbitrary types and forwards them to store them in some location. To store them, values are needed for the function object as well as for the arguments. Thus, std::result_of<...> is used similar to this:
typedef std::result_of<void (*(int))(int&)>::type result_type;
... and since int can't be bound to an int& (int isn't an lvalue type was is needed to be bound to int&), this fails. Failure in this case means that std::result_of<...> doesn't define a nested type.
A follow-up question could be: What is this type used to instantiate std::result_of<...>? The idea is that the function call syntax consisting of ResultType(ArgumentTypes...) is abused: instead of a result type, a function type is passed and std::result_of<...> determines the type of the function called when that function type is called with the given list of arguments is called. For function pointer types it isn't really that interesting but the function type can also be a function object where overloading needs to be taken into account. So basically, std::result_of<...> is used like this:
typedef void (*function_type)(int&);
typedef std::result_of<function_type(int)>::type result_type; // fails
typedef std::result_of<function_type(std::reference_wrapper<int>)>::type result_type; //OK

Function pointers in C++ syntax

I inspected the signature of this right part of this assignment:
creating a thread:
std::thread t2 = std::thread(&Vehicle::addID, &v2, 2);
by hovering with the mouse on and "thread" on the right I got:
std::thread::thread<...>(void (Vehicle::*&&_Fx)(int id), Vehicle &_Ax, int &&_Ax)
Now, I know the basics of C function pointers syntax.
But in C++ you see many times first the class name on the left (especially when using templates)
so I understand that - * within this syntax means a pointer to a (public) member function of the class Vehicle that take an int and returns void (nothing), but whats the && (similar to move constructor) mean?
reference to reference of / take the reference to the member function object by reference??
Notice how the lvalue argument (&v2) becomes an lvalue reference, and the rvalue arguments (the literal 2 and your &Vehicle::addID) become an rvalue reference.
The constructor template you're using is:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
// ^^
We can see there that we ask the computer to take the arguments by "universal reference", i.e. as referency as possible, given each one's value category.
So you're seeing the result of that.
It's not part of the type of the pointer-to-member-function: it's something that's become an rvalue-reference-to-pointer-to-member-function because that's how std::thread takes its arguments, for the purpose of being nice and generic. In the case of a function pointer it's redundant, as there's nothing to "move", but for more complex arguments this can be important.
Of course, due to the nasty "spiral rule" we inherited from C, you end up with the && confusingly plonked in the middle of the pointer's type. 🤪😭
tl;dr:
take the reference [pointer — Ed.] to the member function object by reference??
Pretty much.

std::thread arguments (value vs. const)

When I generate a new thread (std::thread) with a function the arguments of that function
are by value - not by reference.
So if I define that function with a reference argument (int& nArg)
my compiler (mingw 4.9.2) outputs an error (in compilian-suaeli something like
"missing copy constructor" I guess ;-)
But if I make that reference argument const (const int& nArg) it does not complain.
Can somebody explain please?
If you want to pass reference, you have to wrap it into std::reference_wrapper thanks to std::ref. Like:
#include <functional>
#include <thread>
void my_function(int&);
int main()
{
int my_var = 0;
std::thread t(&my_function, std::ref(my_var));
// ...
t.join();
}
std::thread's arguments are used once.
In effect, it stores them in a std::tuple<Ts...> tup. Then it does a f( std::get<Is>(std::move(tup))...).
Passing std::get an rvalue tuple means that it is free to take the state from a value or rvalue reference field in the tuple. Without the tuple being an rvalue, it instead gives a reference to it.
Unless you use reference_wrapper (ie, std::ref/std::cref), the values you pass to std::thread are stored as values in the std::tuple. Which means the function you call is passed an rvalue to the value in the std::tuple.
rvalues can bind to const& but not to &.
Now, the std::tuple above is an implementation detail, an imagined implementation of std::thread. The wording in the standard is more obtuse.
Why does the standard say this happens? In general, you should not bind a & parameter to a value which will be immediately discarded. The function thinks that it is modifying something that the caller can see; if the value will be immediately discarded, this is usually an error on the part of the caller.
const& parameters, on the other hand, do bind to values that will be immediately discarded, because we use them for efficiency purposes not just for reference purposes.
Or, roughly, because
const int& x = 7;
is legal
int& x = 7;
is not. The first is a const& to a logically discarded object (it isn't due to reference lifetime extension, but it is logically a temporary).

C++11 move(x) actually means static_cast<X&&>(x)? [duplicate]

This question already has answers here:
When is the move constructor called in the `std::move()` function?
(2 answers)
Closed 9 years ago.
Just reading Stroustrup's C++ Programming Language 4th Ed and in chapter 7 he says:
move(x) means static_cast<X&&>(x) where X is the type of x
and
Since move(x) does not move x (it simply produces an rvalue reference
to x) it would have been better if move() had been called rval()
My question is, if move() just turns the variable in to an rval, what is the actual mechanism which achieves the "moving" of the reference to the variable (by updating the pointer)??
I thought move() is just like a move constructor except the client can use move() to force the compiler??
what is the actual mechanism which achieves the "moving" of the reference to the variable (by updating the pointer)??
Passing it to a function (or constructor) that takes an rvalue reference, and moves the value from that reference. Without the cast, variables cannot bind to rvalue references, and so can't be passed to such a function - this prevents variables from being accidentally moved from.
I thought move() is just like a move constructor except the client can use move() to force the compiler??
No; it's used to convert an lvalue into an rvalue in order to pass it to a move constructor (or other moving function) which requires an rvalue reference.
typedef std::unique_ptr<int> noncopyable; // Example of a noncopyable type
noncopyable x;
noncopyable y(x); // Error: no copy constructor, and can't implicitly move from x
noncopyable z(std::move(x)); // OK: convert to rvalue, then use move constructor
When you are calling move, you are just telling "Hey, I want to move this object". And when constructor accepts rvalue-reference, it understands it as "Hmm, someone want I move data from this object into myself. So, OK, I'll do it".
std::move does not moves or changes object, it just "marks" it as "ready-for-moving". And only function, that accepts rvalue reference should implement moving actual object.
This is an example, that describes the text above:
#include <iostream>
#include <utility>
class Foo
{
public:
Foo(std::size_t n): _array(new int[n])
{
}
Foo(Foo&& foo): _array(foo._array)
{
// Hmm, someone tells, that this object is no longer needed
// I will move it into myself
foo._array = nullptr;
}
~Foo()
{
delete[] _array;
}
private:
int* _array;
};
int main()
{
Foo f1(5);
// Hey, constructor, I want you move this object, please
Foo f2(std::move(f1));
return 0;
}
As in Going Native 2013, Scott Meyers gave the talk about C++ 11 features, including move.
What std::move essentially do is "unconditionally casts to a rvalue".
My question is, if move() just turns the variable in to an rval, what is the actual mechanism which achieves the "moving" of the reference to the variable (by updating the pointer)??
move does the type casting, thus the compiler will know which ctor to use. The actual move operation is done by the move ctor. You can take it as a function overloading. (ctor overloads with the rvalue parameter type.)
rvalues are generally temporary values which are discarded and destroyed immediately after creation (with a few exceptions). std::string&& is a reference to a std::string that will only bind to an rvalue. Prior to C++11, temporaries would only bind to std::string const& -- after C++11, they also bind to std::string&&.
A variable of type std::string&& behaves much like a bog-standard reference. It is pretty much only in the binding of function signatures and initialization that std::string&& differs from std::string& variables. The other way it differs is when you decltype the reference. All other uses are unchanged.
On the other hand, if a function returns a std::string&&, it is very different than returning a std::string&, because the second kind of thing that can be bound to a std::string&& is the return value of a function returning std::string&&.
std::move is the most common way to generate such a function. In a sense, it lies to the context it is in and tells it "I am a temporary, do with me what you will". So std::move takes a reference to something, and does a cast that makes it pretend to be a temporary -- aka, rvalue.
Move constructors and move assignment and other move-aware functions take an rvalue reference to know when the data they are passed is "scratch" data that they can "damage" to some extent when using it. This is very useful because many types (from containers, to std::function, to anything that uses the pImpl pattern, to non-copyable resources) can have their internal state moved much easier than it can be copied. Such a move changes the state of the source object: but because the function is told it is scratch data, that isn't impolite.
So the move happens not in std::move, but in the function that understands that the return value of std::move implies that it is permitted to modify the data in a somewhat destructive manner if that would help it.
The other ways you can get an rvalue, or an indication that the source object is "scratch data", is when you have a true temporary (an anonymous object created as the return of some other function, or one created using function-style constructor syntax), or when you return from a function with a statement of the form return local_variable;. In both cases, the data binds to rvalue references.
The short version is that std::move does not move, and std::forward does not forward, it just indicates that such an action would be allowed at this point, and lets the function/constructor being called decide what to do with that information.
from http://en.cppreference.com/w/cpp/utility/move
std::move obtains an rvalue reference to its argument and converts it
to an xvalue.
Code that receives such an xvalue has the opportunity to
optimize away unnecessary overhead by moving data out of the argument,
leaving it in a valid but unspecified state.
Return value
static_cast<typename std::remove_reference<T>::type&&>(t)
you can see move is just static_cast
by calling std::move on an object doesn't really doing anything useful, however it tells that the return value can be modified to "a valid but unspecified state"
I thought move() is just like a move constructor except the client can
use move() to force the compiler??
By essentially casting the type to an r-value type, this allows the compiler to invoke the move constructor over the copy constructor.
std::move is equivalent to static_cast<std::string&&>(x).
In the standard, it is defined like this:
template <class T>
constexpr remove_reference_t<T>&& move(T&&) noexcept;
Complementing other answers, an example could help you to better understand how rvalue references work. Take a look to the following code that emulates rvalue references:
#include <iostream>
#include <memory>
template <class T>
struct rvalue_ref
{
rvalue_ref(T& obj) : obj_ptr{std::addressof(obj)} {}
T* operator->() //For simplicity, we'll use the reference as a pointer.
{ return obj_ptr; }
T* obj_ptr;
};
template <class T>
rvalue_ref<T> move(T& obj)
{
return rvalue_ref<T>(obj);
}
template <class T>
struct myvector
{
myvector(unsigned sz) : data{new T[sz]} {}
myvector(rvalue_ref<myvector> other) //Move constructor
{
this->data = other->data;
other->data = nullptr;
}
~myvector()
{
delete[] data;
}
T* data;
};
int main()
{
myvector<int> vec(5); //vector of five integers
std::cout << vec.data << '\n'; //Print address of data
myvector<int> vec2 = move(vec); //Move data from vec to vec2
std::cout << vec.data << '\n'; //Prints zero
//Prints address of moved data (same as first output line)
std::cout << vec2.data << '\n';
}
As we can see, "move" only generates the correct alias, to indicate to the compiler which constructor overload want to use. The difference between this implementation and real rvalue references is of course that casting to rvalue reference has zero overhead, since it's only a compiler directive.

C++0x rvalue references - lvalues-rvalue binding

This is a follow-on question to
C++0x rvalue references and temporaries
In the previous question, I asked how this code should work:
void f(const std::string &); //less efficient
void f(std::string &&); //more efficient
void g(const char * arg)
{
f(arg);
}
It seems that the move overload should probably be called because of the implicit temporary, and this happens in GCC but not MSVC (or the EDG front-end used in MSVC's Intellisense).
What about this code?
void f(std::string &&); //NB: No const string & overload supplied
void g1(const char * arg)
{
f(arg);
}
void g2(const std::string & arg)
{
f(arg);
}
It seems that, based on the answers to my previous question that function g1 is legal (and is accepted by GCC 4.3-4.5, but not by MSVC). However, GCC and MSVC both reject g2 because of clause 13.3.3.1.4/3, which prohibits lvalues from binding to rvalue ref arguments. I understand the rationale behind this - it is explained in N2831 "Fixing a safety problem with rvalue references". I also think that GCC is probably implementing this clause as intended by the authors of that paper, because the original patch to GCC was written by one of the authors (Doug Gregor).
However, I don't this is quite intuitive. To me, (a) a const string & is conceptually closer to a string && than a const char *, and (b) the compiler could create a temporary string in g2, as if it were written like this:
void g2(const std::string & arg)
{
f(std::string(arg));
}
Indeed, sometimes the copy constructor is considered to be an implicit conversion operator. Syntactically, this is suggested by the form of a copy constructor, and the standard even mentions this specifically in clause 13.3.3.1.2/4, where the copy constructor for derived-base conversions is given a higher conversion rank than other user-defined conversions:
A conversion of an expression of class type to the same class type is given Exact Match rank, and a conversion
of an expression of class type to a base class of that type is given Conversion rank, in spite of the fact that
a copy/move constructor (i.e., a user-defined conversion function) is called for those cases.
(I assume this is used when passing a derived class to a function like void h(Base), which takes a base class by value.)
Motivation
My motivation for asking this is something like the question asked in How to reduce redundant code when adding new c++0x rvalue reference operator overloads ("How to reduce redundant code when adding new c++0x rvalue reference operator overloads").
If you have a function that accepts a number of potentially-moveable arguments, and would move them if it can (e.g. a factory function/constructor: Object create_object(string, vector<string>, string) or the like), and want to move or copy each argument as appropriate, you quickly start writing a lot of code.
If the argument types are movable, then one could just write one version that accepts the arguments by value, as above. But if the arguments are (legacy) non-movable-but-swappable classes a la C++03, and you can't change them, then writing rvalue reference overloads is more efficient.
So if lvalues did bind to rvalues via an implicit copy, then you could write just one overload like create_object(legacy_string &&, legacy_vector<legacy_string> &&, legacy_string &&) and it would more or less work like providing all the combinations of rvalue/lvalue reference overloads - actual arguments that were lvalues would get copied and then bound to the arguments, actual arguments that were rvalues would get directly bound.
Clarification/edit: I realize this is virtually identical to accepting arguments by value for movable types, like C++0x std::string and std::vector (save for the number of times the move constructor is conceptually invoked). However, it is not identical for copyable, but non-movable types, which includes all C++03 classes with explicitly-defined copy constructors. Consider this example:
class legacy_string { legacy_string(const legacy_string &); }; //defined in a header somewhere; not modifiable.
void f(legacy_string s1, legacy_string s2); //A *new* (C++0x) function that wants to move from its arguments where possible, and avoid copying
void g() //A C++0x function as well
{
legacy_string x(/*initialization*/);
legacy_string y(/*initialization*/);
f(std::move(x), std::move(y));
}
If g calls f, then x and y would be copied - I don't see how the compiler can move them. If f were instead declared as taking legacy_string && arguments, it could avoid those copies where the caller explicitly invoked std::move on the arguments. I don't see how these are equivalent.
Questions
My questions are then:
Is this a valid interpretation of the standard? It seems that it's not the conventional or intended one, at any rate.
Does it make intuitive sense?
Is there a problem with this idea that I"m not seeing? It seems like you could get copies being quietly created when that's not exactly expected, but that's the status quo in places in C++03 anyway. Also, it would make some overloads viable when they're currently not, but I don't see it being a problem in practice.
Is this a significant enough improvement that it would be worth making e.g. an experimental patch for GCC?
What about this code?
void f(std::string &&); //NB: No const string & overload supplied
void g2(const std::string & arg)
{
f(arg);
}
...However, GCC and MSVC both reject g2 because of clause 13.3.3.1.4/3, which prohibits lvalues from binding to rvalue ref arguments. I understand the rationale behind this - it is explained in N2831 "Fixing a safety problem with rvalue references". I also think that GCC is probably implementing this clause as intended by the authors of that paper, because the original patch to GCC was written by one of the authors (Doug Gregor)....
No, that's only half of the reason why both compilers reject your code. The other reason is that you can't initialize a reference to non-const with an expression referring to a const object. So, even before N2831 this didn't work. There is simply no need for a conversion because a string is a already a string. It seems you want to use string&& like string. Then, simply write your function f so that it takes a string by value. If you want the compiler to create a temporary copy of a const string lvalue just so you can invoke a function taking a string&&, there wouldn't be a difference between taking the string by value or by rref, would it?
N2831 has little to do with this scenario.
If you have a function that accepts a number of potentially-moveable arguments, and would move them if it can (e.g. a factory function/constructor: Object create_object(string, vector, string) or the like), and want to move or copy each argument as appropriate, you quickly start writing a lot of code.
Not really. Why would you want to write a lot of code? There is little reason to clutter all your code with const&/&& overloads. You can still use a single function with a mix of pass-by-value and pass-by-ref-to-const -- depending on what you want to do with the parameters. As for factories, the idea is to use perfect forwarding:
template<class T, class... Args>
unique_ptr<T> make_unique(Args&&... args)
{
T* ptr = new T(std::forward<Args>(args)...);
return unique_ptr<T>(ptr);
}
...and all is well. A special template argument deduction rule helps differentiating between lvalue and rvalue arguments and std::forward allows you to create expressions with the same "value-ness" as the actual arguments had. So, if you write something like this:
string foo();
int main() {
auto ups = make_unique<string>(foo());
}
the string that foo returned is automatically moved to the heap.
So if lvalues did bind to rvalues via an implicit copy, then you could write just one overload like create_object(legacy_string &&, legacy_vector &&, legacy_string &&) and it would more or less work like providing all the combinations of rvalue/lvalue reference overloads...
Well, and it would be pretty much equivalent to a function taking the parameters by value. No kidding.
Is this a significant enough improvement that it would be worth making e.g. an experimental patch for GCC?
There's no improvement.
I don't quite see your point in this question. If you have a class that is movable, then you just need a T version:
struct A {
T t;
A(T t):t(move(t)) { }
};
And if the class is traditional but has an efficient swap you can write the swap version or you can fallback to the const T& way
struct A {
T t;
A(T t) { swap(this->t, t); }
};
Regarding the swap version, I would rather go with the const T& way instead of that swap. The main advantage of the swap technique is exception safety and is to move the copy closer to the caller so that it can optimize away copies of temporaries. But what do you have to save if you are just constructing the object anyway? And if the constructor is small, the compiler can look into it and can optimize away copies too.
struct A {
T t;
A(T const& t):t(t) { }
};
To me, it doesn't seem right to automatically convert a string lvalue to a rvalue copy of itself just to bind to a rvalue reference. An rvalue reference says it binds to rvalue. But if you try binding to an lvalue of the same type it better fails. Introducing hidden copies to allow that doesn't sound right to me, because when people see a X&& and you pass a X lvalue, I bet most will expect that there is no copy, and that binding is directly, if it works at all. Better fail out straight away so the user can fix his/her code.