C++Guns – RoboBlog

02.01.2015

raw speed of C using OO with C++

Filed under: Allgemein — Tags: , , — Thomas @ 20:01

Programs written in C are very very fast. Those written in C++ can be slower due to the fact that copying object is not alway easy as copying an array of numbers. One have to call the copy constructor maybe with side effects like allocate some space.

The language C++ is full backwards compatible to C. So what must we do to use classes and objects with the copy speed of C?

First of all, in C there exist so called POD (plan old data) types like integers, floating point numbers as well as structs und unions. The C language have no class keyword. But classes in C++ can be POD too under certain circumstances. What exactly we need to get a class POD can be read in the C++11 Standard or under [1].
The great benefit of POD types is that it can be copied by simply moving bytes in RAM from one location to another. No call to constructors is needed. That speed up copying enormously.

Enough theory, lets build our own object oriented POD class!
Let's start with a simple class Point that represent a point in 2D. We want to construct a Point object by passing its x and y coordinate. We also want some getter and setter for the coordinates to make the member variables private.

Here is our first implementation:


#include < iostream >
#include < type_traits >

class Point {
public:
  Point() : x(0), y(0) {}
  Point(double x, double y) : x(x), y(y) {}

  void setX(double x) { this->x = x; }
  void setY(double y) { this->y = y; }
  double getX() const { return x; }
  double getY() const { return y; }

private:
  double x, y;
};

int main() {
  Point p(1,2);
  Point p2;

  std::cout << p.getX() << " " << p.getY() << std::endl;

  return 0;
}

Pretty straight forward, right? Save it under point.cpp and compile it with:

$ g++-4.7 -Wall -Wextra -std=c++11 point.cpp 
$ ./a.out 
1 2

I use as compiler gnu g++ version 4.7 to test backwards compatibility. Current is 4.9.2 and 5.0 will be released soon. But you can use any compiler as long it supports c++11. Except for g++ 4.6 thats too old.

To test of a type id POD c++11 provides a simple test [2] which is defined in header file "type_traits". Add this line to our main() function, recompile and run again


std::cout << std::boolalpha;
std::cout << "Point is POD " << std::is_pod::value << "\n";
$ g++-4.7 -Wall -Wextra -std=c++11 point.cpp 
$ ./a.out
1 2
Point is POD false

This shouldn't be too much surprising. As mentioned earlier there are strict rules for when a type is POD. For example the class must be a TrivialType [3]. We can test with is_trivial().


std::cout << "Point is TrivialType " << std::is_trivial::value << "\n";
$ g++-4.7 -Wall -Wextra -std=c++11 point.cpp 
$ ./a.out
1 2
Point is POD false
Point is trivial false

A TrivialType in turn must be TriviallyCopyable [4] and must have Trivial default constructor [5]. Lets test these:


std::cout << "Point is TriviallyCopyable " << std::is_trivially_copyable::value << "\n";
std::cout << "Point is trivially default-constructible " << std::is_trivially_default_constructible::value << "\n";

...

Unfortunately g++ 4.9 does not implement these tests. So we have to wait for version 5.
Instead we can have a closer look about what a "Trivial default constructor" is.

The default constructor for class T is trivial (i.e. performs no action) if all of the following is true:

  • The constructor is not user-provided (that is, implicitly-defined or defaulted)
  • T has no virtual member functions
  • T has no virtual base classes
  • T has no non-static members with brace-or-equal initializers
  • Every direct base of T has a trivial default constructor
  • Every non-static member of class type has a trivial default constructor
  • Right the first condition does not hold. We provide a user default constructor which simply set x and y to zero. Lets remove this constructor and see whats happen:

    $ g++-4.7 -Wall -Wextra -std=c++11 point.cpp 
    point.cpp: In function ‘int main()’:
    point.cpp:20:9: error: no matching function for call to ‘Point::Point()’
    point.cpp:20:9: note: candidates are:
    point.cpp:7:3: note: Point::Point(double, double)
    point.cpp:7:3: note:   candidate expects 2 arguments, 0 provided
    point.cpp:4:7: note: constexpr Point::Point(const Point&)
    point.cpp:4:7: note:   candidate expects 1 argument, 0 provided
    point.cpp:4:7: note: constexpr Point::Point(Point&&)
    point.cpp:4:7: note:   candidate expects 1 argument, 0 provided
    

    It seems we don't have any default constructor anymore. Only the explicit user defined with two arguments and the implicit copy constructor. Thats right. That c++ standard say, that when a explicit user constructor is provided, the compiler don't have to create default constructors.

    With the new 2011 standard we can explicit request a implicit default constructor!
    Replace this line with the following:

    
    Point() : x(0), y(0) {}
    Point() = default;
    
    $ g++-4.7 -Wall -Wextra -std=c++11 point.cpp 
    $ ./a.out 
    1 2
    Point is POD true
    Point is TrivialType true
    

    Congratulations! We have a object oriented class that is as fast as old C style stuff.

    One important note: Variables in C are not automatic initialized! So our class Point is also not default initialized! See [6] for details. You have to call a constructor explicit e.g.
    Point p = Point();

    Here is some nice code to make sure your types are POD. If something goes wrong and the
    type is not POD, it gave an compiler error

    
    #if __cplusplus >= 201103L
    static_assert(!std::is_polymorphic::value, "Please do not add virtual functions to class Point!");
    static_assert(std::is_pod::value, "Class Point is not POD!");
    #endif
    

    The #if __cplusplus stuff is to check if the compiler has enabled c++11 standard.
    Did you know that gnu g++ has set __cplusplus simply to 1 and this bug was know over 10 years?! The reason is very simple: If they fix it, they broke solaris 8. See [7]. Stupid non standard compliant solaris 8 code!

    You can download the example code here point.cpp.zip

    [1] http://en.cppreference.com/w/cpp/concept/PODType
    [2] http://en.cppreference.com/w/cpp/types/is_pod
    [3] http://en.cppreference.com/w/cpp/concept/TrivialType
    [4] http://en.cppreference.com/w/cpp/concept/TriviallyCopyable
    [5] http://en.cppreference.com/w/cpp/language/default_constructor
    [6] http://en.cppreference.com/w/cpp/language/default_initialization
    [7] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=1773

    todo:
    *Ich glaube ja nicht daran, dass das Vorhandensein eines Konstruktors den Code langsamer macht.
    *Eine Sache, die ich unterstreichen würde, ist, dass in C++ "harmlos" aussehender Code sehr ineffizient sein kann
    *Für so eine Behauptung muss man schon vernünftige Benchmarks zeigen
    *C++-03 noch kein Moven ga

    No Comments

    No comments yet.

    RSS feed for comments on this post.

    Sorry, the comment form is closed at this time.

    Powered by WordPress