I am coding my own special container, I want them to be as compatible with STL as possible, including C++14, and modern STL? Even C++17 perhaps.
Should I prepare it to handle ranges? (http://en.cppreference.com/w/cpp/experimental/ranges)
Or should I concentrate in simply providing an iterator interface? For example begin and end?
class MyVector{
class iterator{...}; // nested here for simplicity
iterator begin(){...}
iterator end(){...}
};
In what circumstances the iterator interface (including container and ierator traits) is not enough to build appropriate ranges?
Related
I've inherited a C++98 codebase which has two major uses of memset() on C++ classes, with macros expanded for clarity:
// pattern #1:
Obj o;
memset(&o, 0, sizeof(o));
// pattern #2:
// (elsewhere: Obj *o;)
memset(something->o, 0, sizeof(*something->o));
As you may have guessed, this codebase does not use STL or otherwise non-POD classes. When I try to put as little as an std::string into one of its classes, bad things generally happen.
It was my understanding that these patterns could be rewrited as follows in C++11:
// pattern #1
Obj o = {};
// pattern #2
something->o = {};
Which is to say, assignment of {} would rewrite the contents of the object with the default-initialized values in both cases. Nice and clean, isn't it?
Well, yes, but it doesn't work. It works on *nix systems, but results in fairly inexplicable results (in essence, garbage values) when built with VS2013 with v120_xp toolset, which implies that my understanding of initializer lists is somehow lacking.
So, the questions:
Why didn't this work?
What's a better way to replace this use of memset that ensures that members with constructors are properly default-initialized, and which can preferably be reliably applied with as little as search-and-replace (there are unfortunately no tests). Bonus points if it works on pre-VS2013.
The behavior of brace-initialization depends on what kind of object you try to initialize.
On aggregates (e.g. simple C-style structures) using an empty brace-initializer zero-initializes the aggregate, i.e. it makes all members zero.
On non-aggregates an empty brace-initializer calls the default constructor. And if the constructor doesn't explicitly initialize the members (which the compilers auto-generated constructor doesn't) then the members will be constructed but otherwise uninitialized. Members with their own constructors that initialize themselves will be okay, but e.g. an int member will have an indeterminate value.
The best way to solve your problems, IMO, is to add a default constructor (if the classes doesn't have it already) with an initializer list that explicitly initializes the members.
It works on *nix systems, but results in fairly inexplicable results (in essence, garbage values) when built with VS2013 with v120_xp toolset, which implies that my understanding of initializer lists is somehow lacking.
The rules for 'default' initialization have changed from version to version of C++, but VC++ has stuck with the C++98 rules, ignoring even the updates from C++03 I think.
Other compilers have implemented new rules, with gcc at one point even implementing some defect resolutions that hadn't been accepted for future inclusion in the official spec.
So even though what you want is guaranteed by the standard, for the most part it's probably best not to try to rely on the behavior of initialization of members that don't have explicit initializers.
I think placement new is established enough that it works on VS, so you might try:
#include <new>
new(&o) T();
new(something->p) T();
Make sure not to do this on any object that hasn't been allocated and destructed/uninitialized first! (But it was pointed out below that this might fail if a constructor throws an exception.)
You might be able to just assign from a default object, that is, o = T(); or *(something->p) = T();. A good general strategy might be to give each of these POD classes a trivial default constructor with : o() in the initializer-list.
Consider the following class, with a move constructor and move assignment operator:
class my_class
{
protected:
double *my_data;
uint64_t my_data_length;
}
my_class(my_class&& other) noexcept : my_data_length{other.my_data_length}, my_data{other.my_data}
{
// Steal the data
other.my_data = nullptr;
other.my_data_length = 0;
}
const my_class& operator=(my_class&& other) noexcept
{
// Steal the data
std::swap(my_data_length, other.my_data_length);
std::swap(my_data, other.my_data);
return *this;
}
What is the purpose of noexcept here? I know that is hits to the compiler that no exceptions should be thrown by the following function, but how does this enable compiler optimizations?
The special importance of noexcept on move constructors and assignment operators is explained in detail in https://vimeo.com/channels/ndc2014/97337253
Basically, it doesn't enable "optimisations" in the traditional sense of allowing the compiler to generate better code. Instead it allows other types, such as containers in the library, to take a different code path when they can detect that moving the element types will never throw. That can enable taking an alternate code path that would not be safe if they could throw (e.g. because it would prevent the container from meeting exception-safety guarantees).
For example, when you do push_back(t) on a vector, if the vector is full (size() == capacity()) then it needs to allocate a new block of memory and copy all the existing elements into the new memory. If copying any of the elements throws an exception then the library just destroys all the elements it created in the new storage and deallocates the new memory, leaving the original vector is unchanged (thus meeting the strong exception-safety guarantee). It would be faster to move the existing elements to the new storage, but if moving could throw then any already-moved elements would have been altered already and meeting the strong guarantee would not be possible, so the library will only try to move them when it knows that can't throw, which it can only know if they are noexcept.
IMHO using noexcept will not enable any compiler optimization on its own. There are traits in STL:
std::is_nothrow_move_constructible
std::is_nothrow_move_assignable
STL containters like vector etc use these traits to test type T and use move constructors and assignment instead of copy constructors and assignment.
Why STL use these traits instead of:
std::is_move_constructible
std::is_move_assignable
Answer: to provide strong exception guarantee.
First of all I would remark that in move constructors or move assignment nothing should throw and there seems to be no need to this ever. The only thing which must be done in constructors/assignment operator is dealing with already allocated memory and pointers to them. Normally you should not call any other methods which can throw and your own moving inside your constructor/operator has no need to do so. But on the other hand a simple output of a debug message breaks this rule.
Optimization can be done in a some different ways. Automatically by the compiler and also by different implementations of code which uses your constructors and assignment operator. Take a look to the STL, there are some specializations for code which are different if you use exceptions or not which are implemented via type traits.
The compiler itself can optimize better while having the guarantee that any code did never throw. The compiler have a guaranteed call tree through your code which can be better inlined, compile time calculated or what so ever. The minimum optimization which can be done is to not store all the informations about the actual stack frame which is needed to handle the throw condition, like deallocation variables on the stack and other things.
There was also a question here: noexcept, stack unwinding and performance
Maybe your question is a duplicate to that?
A maybe helpful question related to this I found here: Are move constructors required to be noexcept?
This discuss the need of throwing in move operations.
What is the purpose of noexcept here?
At minimum saving some program space, which is not only relevant to move operations but for all functions. And if your class is used with STL containers or algorithms it can handled different which can result in better optimization if your STL implementation uses these informations. And maybe the compiler is able to get better general optimization because of a known call tree if all other things are compile time constant.
I have a class that's using an std::discrete_distribution which can take an std::initializer_list OR a couple of iterators. My class is in some ways wrapping the discrete_distribution so I really wanted to mimic the ability to take an std::initializer_list which would then be passed down.
This is simple.
However, the std::initializer_list will always be constructed through some unknown values. So, if it was just a std::discrete_distribution I would just construct from iterators of some container. However, for me to make that available via my class, I would need to templatize the class for the Iterator type.
I don't want to template my class because it's only occasionally that it would use the initializer_list, and the cases where it doesn't, it uses an std::uniform_int_distribution which would make this template argument, maybe confusing.
I know I can default the template argument, and I know that I could just define only vector::iterators if I wanted; I'd just rather not.
According to the documentation, std::initializer_list cannot be non-empty constructed in standard C++. BTW, it is the same for C stdarg(3) va_list (and probably for similar reasons, because variadic function argument passing is implementation specific and generally has its own ABI peculiarities; see however libffi).
In GCC, std::initializer_list is somehow known to the C++ compiler (likewise <stdarg.h> uses some builtin things from the C compiler), and has special support.
The C++11 standard (more exactly its n3337 draft, which is almost exactly the same) says in §18.9.1 that std::initializer_list has only an empty constructor and refers to §8.5.4 list-initialization
You probably should use std::vector and its iterators in your case.
As a rule of thumb and intuitively, std::initializer_list is useful for compile-time known argument lists, and if you want to handle run-time known arguments (with the "number" of "arguments" unknown at compile time) you should provide a constructor for that case (either taking some iterators, or some container, as arguments).
If your class has a constructor accepting std::initializer_list<int> it probably should have another constructor accepting std::vector<int> or std::list<int> (or perhaps std::set<int> if you have some commutativity), then you don't need some weird templates on iterators. BTW, if you want iterators, you would templatize the constructor, not the entire class.
There are two types of 3D polys in CGAL, Polyhedron, and Nef_polyhedron. The former allows one to specify an allocator as its fourth template:
http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Polyhedron/Chapter_main.html#Subsection_25.3.5
However, Nef_polyhedron_3 doesn't seem to have that.
What it does have however is iostream operators, to parse to/from an internal string representation:
https://github.ugent.be/divhaere/cgal/blob/master/include/CGAL/Nef_3/SNC_io_parser.h
But that is extremely slow indeed.
Looking at that SNC parser code however, it seems internally it still uses an allocator for its internal structure (an snc object). But even if I could get these to be allocated to my static buffer (to be passed to another process), I can't see anything in the Nef_polyhedron_3 constructors or accessor functions that allows me to reconstruct one.
EDIT: Looking into this a little further, I notice there IS a constructor from an SNC stucture https://github.ugent.be/divhaere/cgal/blob/master/include/CGAL/Nef_polyhedron_3.h :
Nef_polyhedron_3( const SNC_structure& W, SNC_point_locator* _pl,
bool clone_pl,
bool clone_snc) {
And the SNC_structure uses allocators for its internal data (but not for itself):
https://github.ugent.be/divhaere/cgal/blob/master/include/CGAL/Nef_3/SNC_structure.h
Trouble is, that seems to only be set on a compile time basis - I only need to allocate to a specific buffer for polys I know I need to send to another process.
EDIT 2: I just noticed that one of the Nef_polyhedron_3 superclasses is Handle_for:
class Nef_polyhedron_3 : public CGAL::Handle_for< Nef_polyhedron_3_rep<Kernel_, Items_, Mark_> >,
public SNC_const_decorator<SNC_structure<Kernel_,Items_,Mark_> >
In there, that itself uses an allocator too:
https://github.ugent.be/divhaere/cgal/blob/master/include/CGAL/Handle_for.h
I'm still unclear how exactly I plug that in.
Marcos
Nef_polyhedron_3 currently doesn't support custom allocator. However, it is possible to make CGAL use a different allocator through the CGAL_ALLOCATOR macro. However, this will affect all CGAL headers which might be too much. However, it should be possible to add allocator support to the existing code without too much trouble.
I am very new to Windows. While I was working with WMI, I saw there was no use of the term iterator rather enum or enumurator has been used for the same purpose. Do they really have iterators ? or they replace the term, iterator with enum or enum, EnumVariant etc ..... Or I am missing some thing about iterator and enumurator. As far I knew Traditionally the term enum is not same as iterator. Am I wrong ?
Enum is both a thing (a list of possible values) and an action (stepping through each item in a list). The Windows API uses both terms, relying on context to differentiate them.
As a general rule, function and interface names with "Enum" in their name mean enumerate, e.g. EnumWindows means enumerate windows and IEnumUnknown (a COM interface) means enumerate unknown [objects].
The Windows API has no single enumeration methodology. EnumWindows implements the loop internally and repeatedly calls you back via a handler function while IEnumUnknown requires the caller to write the loop using a Next() function.
So, on Windows, an enumerator is a broad class of solutions to the problem of walking through a list of elements.
Iterators are the C++ standard library concept of an enumerator. Choosing 'iterator' instead of 'enumerator' was probably done intentionally to avoid confusion with the existing enum language concept.
Unlike Windows, the C++ standard library iterator concept is very well defined: all iterators work like pointers; all iterators require the caller to write the loop, etc. There are a few classes of iterators in the C++ standard library that allow accessing elements linearly, in reverse, or randomly.
The term enumerator is often used as a synonym for iterator.
An enum, or enumeration, is something else altogether.