Tag: c++

Entries for tag "c++", ordered from most recent. Entry count: 109.

Pages: [1] 2 3 ... 14 >

19:25
Sat
27
Apr 2013

Writing Efficient C++ Code - my Article in ProgramistaMag

I started cooperation with Programista - Polish magazine for programmers and other IT professionals. You can find my first article in the latest issue 4/2013 (11).

My article - "Writing Efficient C++ Code" - is about achieving best possible efficiency of native C++ code. It describes data-oriented design as an alternative to pure object-oriented philosophy and shows its advantages, mostly related to consciously designed layout of data in memory, which makes good use of CPU cache. It also mentions operations that should be avoided if code is to be efficient, shows some language tricks and Visual C++ project options that help with generating efficient code and mentions parallelization.

Besides, in each issue of the magazine you can find interesting articles about different programming languages, libraries and technologies, as well as interviews, book reviews and other articles related to software development. The magazine is available for subscription in electronic and paper form.

Comments (1) | Tags: productions c++ optimization | Author: Adam Sawicki

19:14
Tue
23
Apr 2013

Type Visualization in Visual Studio 2012 Debugger

When you code in C++ and you have your own library of data types, especially containers, it would be nice to be able to see it in the debugger formatted in some readable way. In Visual C++/Visual Studio, there used to be a special file autoexp.dat designed for this purpose, as described in "Writing custom visualizers for Visual Studio 2005". But it had weird syntax and poor error reporting.

Now in Visual Studio 2012 there is a new way of defining debugger visualizations for native data types, called Native Type Visualization Framework (natvis). All you need to do is to create an XML file with ".natvis" extension following special format and place it in directory: %USERPROFILE%\Documents\Visual Studio 2012\Visualizers. Full documentation of this format is on this single MSDN page: "Creating custom views of native objects in the debugger". See also "Expressions in Native C++" and "Format Specifiers in C++".

For example, if you have a singly linked list:

template<typename T>
class CLinkedList {
   // ...
    struct CNode {
       T Value;
       CNode* Next;
    };
    size_t Count;
    CNode* Head;
};

Default visualization of a 3-element object in the debugger would look like this:

But if you create following natvis file:

<?xml version="1.0" encoding="utf-8"?>
<AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
   <Type Name="CLinkedList&lt;*&gt;">
       <DisplayString>{{Count = {Count}}}</DisplayString>
       <Expand>
           <Item Name="[Count]">Count</Item>
           <LinkedListItems>
               <Size>Count</Size>
               <HeadPointer>Head</HeadPointer>
               <NextPointer>Next</NextPointer>
               <ValueNode>Value</ValueNode>
           </LinkedListItems>
       </Expand>
   </Type>
</AutoVisualizer>

Next time you start debugging (restarting Visual Studio is not required), same object will be shown as:

Besides extracting single fields from objects, evaluating whole C++ expressions and formatting values into a string for summary of whole object, this framework is able to visualize following data structures:

Comments (1) | Tags: visual studio debugger c++ | Author: Adam Sawicki

18:16
Sun
25
Nov 2012

C++ is Good for Fast Coding

Many people believe that C and C++ are languages suitable only for coding some special kinds of applications - low level or high performance. I think it's not 100% true. Here is a story: 2011-11-11 we had a game development competition organized in this topic on forum.warsztat.gd, called "Explosive Hamster Exhibition Compo". The name comes from crazy game titles that can be generated by Video Game Name Generator, which was used in this compo to generate a topic, unique for each participant. We had to develop a game in 3 hours. From 3 topics generated for me I chose "Micro Sewer Plus" and made a game about closing sewers. (Download: Reg - MicroSewerPlus.7z - binary + source code, 479 KB.)

I managed to write this simple yet playable game in 3 hours and took 2nd place out of 10, despite my game was written in C++, while many others used the "easier" or "quicker" technologies like Java, JavaScript, XNA o Game Maker. What I want to show here is that C++ is not necessarily a language in which coding is hard and slow. It's all about having a good framework - a library with a set of functions and classes that handles all low-level stuff and allows you to implement the game itself quickly, easily and directly as you think about it. You don't have to manually free all allocated memory if you have smart pointers. You don't have to write shaders and setup Direct3D render states if you have Canvas class with methods like DrawSprite(x, y, color).

You can prepare a good library by yourself or download one of many freely available on the Internet and use just like in any other programming language. What you get in return when deciding to use C++ is great flexibility in defining how the interface of your library looks like. Thanks to templates, operator overloading and all that stuff you can create your own domain-specific language inside C++ (like the << operator is used to write to stream objects). At the same time, due to compiling to native code, creating objects on the stack and other language features you don't have to sacrifice performance. You don't have to use separate variables float x, y, z or dynamically allocate new Vector(x, y, z). You can define a vector structure with overloaded operators, use it conveniently and compiler will optimize the code so you can do thousands or millions of vector computations per second.

Comments (6) | Tags: c++ warsztat compo productions | Author: Adam Sawicki

20:47
Sun
21
Oct 2012

C++ Lambdas - A Simple Explanation

Much can be said about theory behind lambda expressions, but lambdas in C++ - this new feature of C++11 supported by Visual C++ 2010, 2012, as well as other new compilers - can be explained very simply by following example. Today I wanted to write code that would sort a vector of pointers to entities in my 3D scene by distance from the camera, to ensure correct rendering of translucent objects.

std::vector<CEntity*> entitiesToRender;
vec3 cameraEyePos;
vec3 cameraForwardDir;

Vector in world space pointing forward from the camera - towards its positive Z axis - can be extracted from 3rd column of the view matrix. Dot product between this vector and a vector from camera position to object position gives length of the projection of one vector onto the other, which is the distance from the camera. But that's not the point here.

If you use STL, you know it's convenient to sort a vector using std::sort algorithm. Except if the contained type does not have operator< or you don't want it to be used (like here, as it would just compare pointers), you have to write a functor to compare elements. Lambda simplifies this task:

std::sort(
    entitiesToRender.begin(),
    entitiesToRender.end(),
    [=](CEntity* lhs, CEntity* rhs)
{
    return
        dot(lhs->GetPosition() - cameraEyePos, cameraForwardDir) >
        dot(rhs->GetPosition() - cameraEyePos, cameraForwardDir);
});

This code is equivalent to the traditional, more verbose version using functor:

class CompareFunctor
{
public:
    CompareFunctor(const vec3& cameraEyePos, const vec3& cameraForwardDir) :
        m_CameraEyePos(cameraEyePos),
        m_CameraForwardDir(cameraForwardDir)
    {
    }

    bool operator()(CEntity* lhs, CEntity* rhs) const
    {
        return
            dot(lhs->GetPosition() - m_CameraEyePos, m_CameraForwardDir) >
            dot(rhs->GetPosition() - m_CameraEyePos, m_CameraForwardDir);
    }

private:
    vec3 m_CameraEyePos;
    vec3 m_CameraForwardDir;
};

std::sort(
    entitiesToRender.begin(),
    entitiesToRender.end(),
    CompareFunctor(cameraEyePos, cameraForwardDir));

Parameters of lambda inside () are data passed to every call, like parameters of operator() in the functor. Inside [] we can specify what parameters are captured from the current context (local variables), which is equivalent to storing them as member variables inside the functor. [=] means capturing all necessary parameters by value, which are cameraEyePos and cameraForwardDir in this case. [&] would remember them by reference.

Comments (14) | Tags: c++ | Author: Adam Sawicki

15:03
Sun
30
Sep 2012

CppDepend

Recently I've played a little bit with CppDepend - a commercial static code analysis tool for C++. Windows and Linux versions are available and you can download 14-days trial version. You can find lots of information about the program on their website, including screenshots, sample reports, and cases studies of Ogre3D and Irrlicht game engines. Here is my brief review.

At first glance, program looks like typical commercial Windows application full of colourful icons, popup windows, hints and tips everywhere. They have their own, non-standard looking GUI, but it clearly resembles the one from Visual Studio, including docking side panels, error list at the bottom etc. Skin can be changed to make the program look like GUI from different versions of Microsoft Office, among others. Even the HTML report is full of JavaScript and knows better than you when you want to open a link in new window (that is, in most cases). But after getting used to it I think everything is designed reasonably and makes this powerful application really easy to use.

First thing you have to do is to create a CppDepend project. You can add Visual Studio solutions to it and set parameters about what reports you want. Alternatively, if you don't have one beacuse e.g. you use makefiles, you can use separate tool - ProjectMaker - to manually create and save some virtual .sl "solution" that enlists source files and directories to analyze.

Then the program analyzes your code (internally using Clang) and builds a database about it. It generates report in HTML format, as well as allows browsing gathered data interactively inside the program (or inside Visual Studio if you install appropriate AddIn). Here you can see how it looks like for some of my code, combined The Final Quest 7 and CommonLib. First of all, you can browse tree of projects, namespaces, classes and methods:

A HTML raport is generated with the list of found issues:

You can visualize different kinds of relationships like inheritance or just using one type by another as a graph:

Another way to visualize dependencies is matrix:

Yet another view mode is treemap. Here I displayed methods (grouped in classes and modules) where size of a method is dependent on number of lines of code.

You can perform simple search and sorting of projects, namespaces, types, methods and files by name, size and different other metrics. Matched items are highlighted on the treemap.

Finally, you can issue complex queries using CQLinq - a query language based on C# LINQ syntax. Embedded query editor is available with syntax highlighting, autocompletion and immediate query output as you type.

So what kinds of data does the program gather from your code? A lot of. Even such simple thing as number of lines of code is calculated intelligently. Instead of text-based, these are logical LOC, which count sequence points in code, so they are independent of coding style, like braces placement or spanning function call on several lines of code.

I didn't mess with code metrics before, so it was interesting for me to read what does it mean for a piece of code to be "stable" or "abstract". It turns out that the code is stable if its types are used by a lot of types of third-party modules. On the other hand, code is abstract when it contains a lot of abstract classes and interfaces. Code that is stable but not abstract can be painful to modify. Code that is not stable and very abstract is useless. Sounds like an interesting idea :)

Another interesting metric is Cyclomatic Complexity. It is basically a number of decision that can be taken in a function, that is number of: if, while, for, case, default, continue, goto, catch etc. Lack of Cohesion Of Methods (LCOM) is yet another metric. It can indicate quality of a class. It is low when almost every methods in the class uses every field, which is good. It is high when, for example, every method uses only one field (like when class has only getters and setters), which is bad.

Based on these metrics (and many others) and some predefined rules, a list of issues found in the code is enlisted in the report. Some of them are very valuable, some not so much. For example, code matching the rule "Constructor should not call a virtual methods" is obviosly a bug or at least a bad practice. But the rule "Fields should be declared as private" seems a little too restrictive, especially as it matches also globals like const float PI = 3.14.

Generally, it feels great to have analysis based on both physical aspect (like directory structures, source files, comments) and logical aspect of the code (like class inheritance, public versus private, number of nested loops). It's also great that the program analyzes code on all levels, from whole solution depending on external (and possibly unknown) code like Windows.h, through namespaces, classes and methods, down until analyzing code inside functions, counting number of conditions, loops, local variables and analyzing which classes and methods are used by which.

Static code analysis tool like CppDepend is not one of the tools necessary for programming, like editor, compiler or debugger. But I believe it can be useful in at least following applications:

When thinking about a conclusion, I have this thought based on some blogs posts I've read recently (here is the first one, unfortunately I can't find the other one right now) that there is a spectrum of different types of programmers. On one side, there are these very "good", rockstar programmers who are not as good at teamwork and instead of solving real practical problems, they play around with code, talk about theory (whether algorithms or language standard) and write so sophisticated code (e.g. with elaborate C++ template tricks) that it is hard to read and maintain for others. They don't bother to give their variables some meaningful names or split their code into clear modules and classes. On the other side of the spectrum there is the growing number of bad programmers who graduate computer science because they were told to do so (with a promise for good money, lots of jobs or anything) and have no real talent, passion or even basic willingness to learn this profession. They only glue their code using ready frameworks, design patterns and code found on Google using Ctrl+C Ctrl+V. I can see clear relationship between this spectrum and the seriousness with which we take reports about code metrics like these genetared by CppDepend. I also believe that in both cases the best approach lies somewhere in the middle.

Appendix: Clang Rocks! is an interesting article by Issam Lahlali, CppDepend lead developer, that explains how they use Clang frontend to analyze C++ code in their product.

Comments (4) | Tags: c++ tools | Author: Adam Sawicki

23:37
Wed
02
May 2012

Functional Programming is the New Trend

Some time ago I've written about data-oriented design as a popular trend among game developers, opposite to the belief that object-oriented programming is the silver bullet for all challenges and complexities of programming. Mike Acton, Engine Director at Insomniac Games and the creator of #AltDevBlogADay, is probably the biggest evangelist of this idea.

Now I can see that functional programming is a concept gaining popularity and it seems to follow similar mindset. Of course we won't start coding our games and programs in Lisp or Haskell tomorrow, but some of the ideas coming from functional languages can be applied to thinking about our everyday C++ code, instead of seeing design patterns, singletons and class inheritance everywhere. This can mean, for example, making data const (immutable) wherever possible and writing functions as pure - returning processed data that depend only on input data and not mutating or accessing any global state. This makes code simpler to read and understand, debug and unit-test, as well as to parallelize.

I've seen some voices in gamedev advocating that functional programming is the future even years ago. I can remember slides from some conference about it, I can't find it now though. But recently more and more programmers seem to be interested in learning some functional languages, writing about it, like explaining what the monad is etc. Some really recent, interesting blog posts about applying idea of functional programming in the real code:

Life Without Objects by Chris Turner
(Almost) functional programming tips for C++ by Bryan St. Amour
And finally, a post from #AltDevBlogADay by John Carmack: Functional Programming in C++.

By the way, it really impresses me how despite all his experience, fame and success, Carmack still tweets and blogs about programming, down to its dirtiest details, instead of writing about management, leadership, enterpreneurship, money, psychology, recruitment etc., like many other professionals do.

Comments (5) | Tags: c++ | Author: Adam Sawicki

20:48
Mon
16
Apr 2012

Redirecting Output to File in Visual C++

If you write a console program in C++ that prints
 a lot of text to the standard output, sometimes watching these few newest line that appear in the black system console is not enough. When running the program from command line, you can redirect its output to a text file with syntax like > Output.txt.

What about launching program from Microsoft Visual Studio / Visual C++ Express? Can you redirect console output to file from there? There is no field for it in project properties, but it actually works when you just append the redirect symbol to Command Arguments field, like this:

Comments (4) | Tags: c++ visual studio | Author: Adam Sawicki

17:00
Sat
14
Apr 2012

unique_ptr in Visual C++ 2010

Sure C++ doesn't have garbage collector, but the way of freeing memory and other resources recommended for this language is RAII idiom - creating classes (like smart pointers) that free pointed object in destructor. Standard library of old C++ provided only auto_ptr class for this, which had many flaws. Some programmers have been writing their own smart pointer classes or using these from Boost library - like scoped_ptr and shared_ptr.

The new C++11 standard (called C++0x before release) defines new smart pointers, similar to these from Boost. They are called unique_ptr and shared_ptr, they exist in std namespace and require #include <memory>. Microsoft Visual Studio 2010 / Visual C++ Express 2010 already implement parts of this new standard. Language features like r-value reference and move semantics make these smart pointers more powerful than before.

shared_ptr is for shared ownership and uses reference counting, so it's not needed very often in my opinion. More often we are dealing with a situation where there is one, clearly stated owner of a dynamically allocated object, like a local variable in some scope or a class member. So let's take a look at how unique_ptr can be used for this:

std::unique_ptr<MyClass> ptr1(new MyClass());
// ptr1 will automatically call destructor and free the object when going out of scope.

std::unique_ptr<MyClass> ptr2; // ptr2 is NULL
ptr2.reset(new MyClass(1)); // Object is created and passed to smart pointer.
ptr2->m_Number = 2; // Object can be dereferenced like with normal pointer.
ptr2.reset(new MyClass(3)); // New object is given to the pointer. First one is destroyed.
ptr2.reset(); // Second object is destroyed. ptr2 is now NULL.

unique_ptr can be used for arrays:

std::unique_ptr<MyClass[]> arrPtr(new MyClass[6]); // Smart pointer to array.
arrPtr[2].m_Number = 10; // Indexing array like with normal pointer.
// arrPtr will free the array with delete[] when going out of scope.

unique_ptr cannot be copied, but thanks to r-value references and move semantics introduced in C++11 it can be moved, so it can also be passed as parameter and returned by value, like this:

typedef std::unique_ptr<MyClass> MyClassPtr;

MyClassPtr ProducePtr() {
    MyClassPtr ptr = MyClassPtr(new MyClass());
    ptr->m_Number = 123;
    return ptr;
}

void ConsumePtr(MyClassPtr ptr) {
    printf("The number was %d\n", ptr->m_Number);
}

ConsumePtr(ProducePtr());

MyClassPtr ptr = ProducePtr();
ptr->m_Number = 456;
ConsumePtr(std::move(ptr));

Unlike old scoped_ptr from Boost, unique_ptr from C++11 can be used inside STL containers, e.g. std::vector. Reallocation that happens inside vector will not corrupt it.

std::vector<MyClassPtr> vec;
vec.push_back(MyClassPtr(new MyClass(1)));
vec.emplace_back(new MyClass(2)); // A new, better way of adding elements.

for(auto it = std::begin(vec); it != std::end(vec); ++it)
    printf("%d\n", (*it)->m_Number);

And now the most interesting part - custom deleters! unique_ptr can be used to store any resources because you can provide it with your own code that will be used to free that resource. For example, you can print something to console before deleting object :) Deleter can be a functor passed as second template parameter:

struct MyDeleter {
    void operator()(int* ptr) const {
        printf("Deleting int!\n");
        delete ptr;
    }
};

std::unique_ptr<int, MyDeleter> ptr1(new int(1));

Deleter can also hold some state. This way you can associate additional information with the pointer, like a memory pool that the pointer object comes from. Now the sizeof(ptr3) will be 8 because it must hold deleter data next to the pointer.

class MyComplexDeleter {
public:
    MyComplexDeleter(int memoryPool) : m_MemoryPool(memoryPool) {
    }
    void operator()(int* ptr) const {
        printf("Deleting from memory pool %d\n", m_MemoryPool);
        delete ptr;
    }
private:
    int m_MemoryPool;
};

MyComplexDeleter deleterForPool20(20);
std::unique_ptr<int, MyComplexDeleter> ptr3(new int(3), deleterForPool20);

Deleter can also be a normal function, like fclose:

std::unique_ptr<FILE, int(*)(FILE*)> filePtr(
    fopen("Readme.txt", "rb"),
    fclose);

unique_ptr<int> will contain value of type int*. What if we want to store a resource using unique_ptr that is not a pointer but some handle or identifier, so this automatically added * is undesirable? It turns out that the type of stored value can be changed by defining "pointer" type inside deleter.

struct CloseHandleDeleter {
    typedef HANDLE pointer;
    void operator()(HANDLE handle) const { CloseHandle(handle); }
};

std::unique_ptr<HANDLE, CloseHandleDeleter> file(CreateFile(
    "Readme.txt", GENERIC_READ, FILE_SHARE_READ, NULL,
    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
// The first template parameter of unique_ptr seem to not have any menaing in this case.

Comments (5) | Tags: c++ visual studio | Author: Adam Sawicki

Pages: [1] 2 3 ... 14 >

RSS: RSS Feed: Adam Sawicki - Homepage (Blog)

STAT NO AD [Stat] [Admin] [STAT NO AD] [pub] [Mirror] Copyright © 2004-2013 Adam Sawicki
Copyright © 2004-2013 Adam Sawicki