I have hard time to understand following concepts:
is_trivially_copyable
is_trivially_copy_assignable
is_trivially_copy_constructible
is_trivially_destructible
is_trivially_move_assignable
Take for example std::string_view.
#include <string_view>
int main(){
using sv = std::string_view;
// static_assert(std::is_trivial_v<sv> );
static_assert(std::is_trivially_copyable_v<sv> );
static_assert(std::is_trivially_copy_assignable_v<sv> );
static_assert(std::is_trivially_copy_constructible_v<sv> );
static_assert(std::is_trivially_destructible_v<sv> );
static_assert(std::is_trivially_move_assignable_v<sv> );
}
My question is which of these, imply others, so I can to less static_assert's in my code?
I know is_trivial imply all of these,
Note I am not interested in c-tors:
is_trivially_constructible
is_trivially_default_constructible
std::is_trivially_copyable covers the rest, though allows for the relevant methods to be deleted. It says:
If T is a TriviallyCopyable type, provides the member constant value equal true. For any other type, value is false.
And requirements for TriviallyCopyable are:
Every copy constructor is trivial or deleted
Every move constructor is trivial or deleted
Every copy assignment operator is trivial or deleted
Every move assignment operator is trivial or deleted
at least one copy constructor, move constructor, copy assignment operator, or move assignment operator is non-deleted
Trivial non-deleted destructor
You can even check llvm implementation.
This is related to the rule of zero.
AFAIK rest of the test are basic and unrelated to each other in terms of logical implications.
Apart from tests you mention is_copy_assignable and is_copy_constructible (and possibly other "copy" versions) can be formulated in terms of no-copy tests e.g. is_assignable. But this is something different, since checking for "copy" is just adding additional type constraint.
Related
I want to accept classes which are "trivially copyable", in the sense that if I mem-copy the byte representation of one variable of the type into another, it will be usable, and nothing will have been broken in any way.
Looking at std::is_trivially_copyable, I see the requirements are:
Trivially copyable classes, i.e. classes satisfying following requirements:
At least one copy constructor, move constructor, copy assignment operator, or move assignment operator is eligible
Every eligible copy constructor (if any) is trivial
Every eligible move constructor (if any) is trivial
Every eligible copy assignment operator (if any) is trivial
Every eligible move assignment operator (if any) is trivial
Has a trivial non-deleted destructor
First and last requirement - check. But the other requirements are super-strong and not what I want! I'd be willing to "compromise" on having a trivial copy ctor as a requirement, and that's already quite different than what I really want.
So, what type trait can I use from the standard library, or write myself, to express the constraint I'm interested in?
I'm writing C++11 right now, so if your answer requires a later standard - write it, but mention that fact explicitly.
At least one copy constructor, move constructor, copy assignment operator, or move assignment operator is eligible
Has a trivial non-deleted destructor
First and last requirement - check. But the other requirements are super-strong
So, what type trait can I use from the standard library, or write myself, to express the constraint I'm interested in?
You could use (is_copy_constructible || is_move_constructible || is_assignable) && std::is_trivially_destructible.
I'd be willing to "compromise" on having a trivial ... copy ctor as a requirement
You could use std::is_trivially_copy_constructible.
if I mem-copy the byte representation of one variable of the type into another, it will be usable, and nothing will have been broken in any way.
However, those requirements won't be sufficient for this. You need the "super-strong" requirements for this. This is what std::is_trivially_copyable is for.
When a class explicitly declares a copy operation (i.e., a copy constructor or copy assignment operator), move operations are not declared for the class. But when a class explicitly declares a move operation, the copy operations are declared as deleted. Why does this asymmetry exist? Why not just specify that if a move operation is declared, no copy operations will be declared? From what I can tell, there would not be any behavioral difference, and there would be no need for the asymmetric treatment of move and copy operations.
[For people who like citations of the standard, the lack of declaration of move operations for classes with copy operation declarations is specified in 12.8/9 and 12.8/20, and the deleted copy operations for classes with move operation declarations are specified in 12.8/7 and 12.8/18.]
When a class would be moved but for the fact that no move constructor is declared, the compiler falls back to copy constructor. In the same situation, if move constructor is declared as deleted, the program would be ill-formed. Thus, if move constructor were implicitly declared as deleted, a lot of reasonable code involving existing pre-C++11 classes would fail to compile. Things like myVector.push_back(MyClass())
This explains why move constructor cannot be implicitly declared deleted when copy constructor is defined. This leaves the question of why copy constructor is implicitly declared deleted when move constructor is defined.
I don't know the exact motivation of the committee, but I have a guess. If adding a move constructor to existing C++03-style class were to remove a (previously implicitly defined) copy constructor, then existing code using this class may change meaning in subtle ways, due to overload resolution picking unexpected overloads that used to be rejected as worse matches.
Consider:
struct C {
C(int) {}
operator int() { return 42; }
};
C a(1);
C b(a); // (1)
This is a legacy C++03 class. (1) invokes an (implicitly defined) copy constructor. C b((int)a); is also viable, but is a worse match.
Imagine that, for whatever reason, I decide to add an explicit move constructor to this class. If the presence of move constructor were to suppress the implicit declaration of copy constructor, then a seemingly unrelated piece of code at (1) would still compile, but silently change its meaning: it would now invoke operator int() and C(int). That would be bad.
On the other hand, if copy constructor is implicitly declared as deleted, then (1) would fail to compile, alerting me to the problem. I would examine the situation and decide whether I still want a default copy constructor; if so, I would add C(const C&)=default;
Why does this asymmetry exist?
Backward compatibility, and because the relationship between copying and moving is already asymmetrical. The definition of MoveConstructible is a special case of CopyConstructible, meaning that all CopyConstructible types are also MoveConstructible types. That's true because a copy constructor taking a reference-to-const will handle rvalues as well as lvalues.
A copyable type can be initialized from rvalues without a move constructor (it just might not be as efficient as it could be with a move constructor).
A copy constructor can also used to perform a "move" in implicitly-defined move constructors of derived classes when moving the base sub-object.
So a copy constructor can be seen as a "degenerate move constructor", so if a type has a copy constructor it doesn't strictly need a move constructor, it is already MoveConstructible, so simply not declaring the move constructor is acceptable.
The opposite is not true, a movable type is not necessarily copyable, e.g. move-only types. In those cases, making the copy constructor and assignment deleted provides better diagnostics than just not declaring them and getting errors about binding lvalues to rvalue references.
Why not just specify that if a move operation is declared, no copy operations will be declared?
Better diagnostics and more explicit semantics. "Defined as deleted" is the C++11 way to clearly say "this operation is not allowed", rather than just happening to be omitted by mistake or missing for some other reason.
The special case of "not declared" for move constructors and move assignment operators is unusual and is special because of the asymmetry described above, but special cases are usually best kept for a few narrow cases (it's worth noting here that "not declared" can also apply to the default constructor).
Also worth noting is that one of the paragraphs you refer to, [class.copy] p7, says (emphasis mine):
If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.
"The latter case" refers to the "otherwise, it is defined as defaulted" part. Paragraph 18 has similar wording for the copy assignment operator.
So the intention of the committee is that in some future version of C++ other types of special member function will also cause the copy constructor and copy assignment operator to be deleted. The reasoning is that if your class needs a user-defined destructor then the implicitly-defined copy behaviour is probably not going to do the right thing. That change hasn't been made for C++11 or C++14 for backward compatibility reasons, but the idea is that in some future version to prevent the copy constructor and copy assignment operator being deleted you will need to declare them explicitly and define them as defaulted.
So deleting copy constructors if they might not do the right thing is the general case, and "not declared" is a special case just for move constructors, because the copy constructor can provide the degenerate move anyway.
It is essentially to avoid migrated code to perform unexpected different actions.
Copy and move require a certain level of coherence, so C++11 -if you declare just one- suppress the other.
Consider this:
C a(1); //init
C b(a); //copy
C c(C(1)); //copy from temporary (03) or move(11).
Suppose you write this in C++03.
Suppose I compile it later in C++11.
If no ctor are declared, the default move does a copy (so the final behavior is the same as C++03).
If copy is declared, move is deleted, and sine C&& decays into C const& The third statement result in a copy from a temporary. This is still a C++03 identical behavior.
Now, if I'm adding later a move ctor, it means I'm changing the behavior of C (something you did not plan when defining C in C++03), and since a movable object does not need to be copyable (and vice versa), The compiler assumes that by making it movable, the dafault copy may be not anymore adequate. It's up to me to implementing it in coherence with the move or -if I found it adequate- restore the C(const C&)=default;
Given that a class actually is moveable, manually implementing the move constructor and move assignment operator for a class quickly become tedious.
I was wondering when doing so is actually a heavy, heavy, premature optimization?
For instance, if a class only has trivial POD data or members that themselves have move constructor and move assignment operator defined, then I'd guess that the compiler will either just optimize the shit out of the lot (in the case of PODs) and otherwise use the members' move constructor and move assignment operator.
But is that guaranteed? In what scenarios should I expect to explicitly need to implement a move constructor and move assignment operator?
EDIT: As mentioned below by Nicol Bolas in a comment to his answer at https://stackoverflow.com/a/9966105/6345, with Visual Studio 11 Beta (and before) no move constructor or move assignment operator is ever automatically generated. Reference: http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx
If you find yourself implementing, any of:
destructor
copy constructor
copy assignment
Then you should be asking yourself if you need to implement move construction. If you "= default" any of the above, you should be asking yourself if you should then also "= default" the move members.
Even more importantly, you should be documenting and testing your assumptions, for example:
static_assert(std::is_nothrow_default_constructible<A>::value, "");
static_assert(std::is_copy_constructible<A>::value, "");
static_assert(std::is_copy_assignable<A>::value, "");
static_assert(std::is_nothrow_move_constructible<A>::value, "");
static_assert(std::is_nothrow_move_assignable<A>::value, "");
static_assert(std::is_nothrow_destructible<A>::value, "");
First, move semantics only help for classes that hold resources of any kind. "Flat" classes don't benefit from it at all.
Next, you should build your classes out of "building blocks", like vector, unique_ptr and the likes, that all deal with the nitty-gritty low-level detail of resources. If your class is done as such, you won't have to write anything at all since the compiler will generate the members correctly for you.
If you need to write a destructor for, say, logging, generation of move ctors will be disabled, so you need a T(T&&) = default; for compilers that support it. Otherwise, this is one of the only places were to write such a special member yourself (well, except if you write such a "building block").
Note that the logging in the destructor and constructor can be done an easier way. Just inherit from a special class that logs on construction / destruction. Or make it a member variable. With that:
tl;dr Let the compiler generate the special member for you. This also counts for copy constructor and assignment operator, aswell as the destructor. Don't write those yourself.
(Okay, maybe the assignment operators, if you can identify them as a bottle neck and want to optimize them, or if you want special exception safety or somesuch. Though, the "building blocks" should already provide all that.)
Do it every time the default behavior is undesirable or every time the default ones have been deleted and you still need them.
The compiler default behavior for move is call the member and base move. For flat classes / buil-in types this is just like copy.
The problem is typically present with classes holding pointers or value representing resources (like handle, or particular indexes etc) where a move requires to copy the values in the new place, but also to set the old place to some "null state value" recognizable by the destructor. In all other cases, the default behavior is OK.
The problem may also arise when you define a copy (and the compiler deletes the default move) or a move (and the compiler deletes the default copy), and you need them both. In these cases, re-enabling the default may suffice.
In what scenarios should I expect to explicitly need to implement a move constructor and move assignment operator?
Under the following cases:
When you are using Visual Studio 10 or 11. They implement r-value references, but not compiler generated move semantics. So if you have a type that has members that need moving or even contains a moveable type (std::unique_ptr, etc), you must write the move yourself.
When you might need copy constructors/assignment operators and/or a destructor. If your class contains something that made you manually write copy logic or needs special cleanup in a destructor, odds are good that you'll need move logic too. Note that this includes deleting copy mechanisms (Type(const Type &t) = delete;). If you don't want to copy the object, then you probably need move logic or to delete the move functions too.
As others have said, you should try to keep the number of types that need explicit move or copy mechanisms to a bare minimum. Put these in utility "leaf" classes, and have most of your classes rely on the compiler-generated copy and move functions. Unless you're using VS, where you don't get those...
Note: a good trick with move or copy assignment operators is to take them by value:
Type &operator=(Type t) { std::swap(*this, t); return *this; }
If you do this, it will cover both move and copy assignment in one function. You still need separate move and copy constructors, but it does reduce the number of functions you have to write to 4.
The downside is that you're effectively copying twice if Type is made of only basic types (first copy into the parameter, second in swap). Of course, you have to implement/specialize swap, but that's not difficult.
I'm sorry. I may have missed the point of your question. I'm taking your question to mean copy constructors.
Back in the 1990s when I learned C++, I was taught always to write a copy constructor when designing a class. Otherwise, and this may have changed with newer versions of the compiler, C++ will generate a copy constructor for you in the situations that require one.
That default copy constructor may not always work the way you want. This would especially be true if your class contains pointers, or you otherwise do not want the default byte-wise copy of a default copy constructor.
Finally, I was taught that by writing a copy constructor, you are taking exact control over how you want your class copied.
I hope this helps.
A C++ wiki book refers to
... In C++0x, such an assignment operator is known as a unifying
assignment operator because it eliminates the need to write two
different assignment operators ...
for an assignment operator that takes it's class type by value:
String & operator = (String s) // the pass-by-value parameter serves as a temporary
{
s.swap (*this); // Non-throwing swap
return *this;
}
I tried googling the term, but it doesn't appear to be in widespread use.
Where does it come from?
It appears to be in reference to the unification that takes place in formal type systems. The thought is if the r- and l-values can be brought to the same type (unified) by only certain, legal substitutions, then the assignment is well-formed.
Wikipedia claims the idea was first given meaningful attention (and possibly its name) by John Alan Robinson.
I'm not sure who phrased it but the wiki book is wrong. The word "unifying" appears exactly zero times in the c++0x "standard" (you should really be using the phrase "C++11" nowadays, it was approved in August 2011).
The correct term is copy elision. From C++0x (n3242, the last I can get without shelling out money), section 12.8 Copying and moving class objects, /34:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects.
In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies) ...
Considering the high quality of today's compilers regarding return value optimization (both RVO and NRVO), I was wondering at what class complexity it's actually meaningful to start adding move constructors and move assignment operators.
For instance, for this really_trivial class, I just assume that move semantics cannot offer anything more than RVO and NRVO already does when copying around instances of it:
class really_trivial
{
int first_;
int second_;
public:
really_trivial();
...
};
While in this semi_complex class, I'd add a move constructor and move assignment operator without hesitation:
class semi_complex
{
std::vector<std::string> strings_;
public:
semi_complex(semi_complex&& other);
semi_complex& operator=(semi_complex&& other);
...
};
So, at what amount and of what kinds of member variables does it start making sense to add move constructors and move assignment operators?
It is already meaningful for purely semantic reasons, even if you keep the optimization-aspects out completely. Just imagine the case where a class does not/cannot implement copying. For example boost::scoped_ptr cannot be copied, but it can be moved!
In addition to the excellent answers already given, I would like to add a few forward-looking details:
There are new rules in the latest C++0x draft for automatically generating a move constructor and move assignment operator. Although this idea is not entirely new, the latest rules have only been in the draft since Oct. 2010, and not yet widely available in compilers.
If your class does not have a user-declared copy constructor, copy assignment operator, move constructor, move assignment operator and destructor, the compiler will provide defaulted move constructor and move assignment operator for you. These default implementations will simply member-wise move everything.
You can also explicitly default your move members:
semi_complex(semi_complex&&) = default;
semi_complex& operator=(semi_complex&&) = default;
Note that if you do so, you will implicitly inhibit copy semantics unless you explicitly supply or default the copy constructor and copy assignment operator.
In a closely related late-breaking change: If your class has an explicit destructor, and implicit copy members, the implicit generation of those members is now deprecated (the committee would like to remove the implicit generation of copy when there is an explicit destructor, but can't because of backwards compatibility).
So in summary, any time you have a destructor declared, you should probably be thinking about explicitly declaring both copy and move members.
As a rule of thumb I would say add a move constructor whenever you have member variables which hold (conditionally) dynamically allocated memory. In that case its often cheaper if you can just use the existing memory and give the move source the minimal allocation it needs so it can still function (meaning be destroyed). The amount of member variables doesn't matter that much, because for types not involving dynamic memory its unlikely to make a difference whether you copy or move them (even the move constructor will have to copy them from one memory location to another somehow).
Therefore move semantices make sense, when
dynamic memory allocation is involved
move makes sense for one or more member variables (which means those involve dynamic allocation somewhere along the line).
Typically, moving makes sense when the class holds some kind of resource, where a copy would involve copying that resource and moving would not. The easiest example is dynamically allocated memory. However, it is worth noting that the compiler will automatically generate move constructors and operators, just like it will for copying.
Irrespective of anything that might be automatically done by the compiler I'd say that:
If any member has meaningful and beneficial move semantics, that the class should have this move semantics too. (-> std::vector members)
If any dynamic allocations are involved when copying, move operations make sense.
Put otherwise, if move can do something more efficiently than copy, it makes sense to add it. In your really_trivial a move could only be as efficient as the copy already is.