Tag: c++

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

Warning! Some information on this page is older than 6 years now. I keep it for reference, but it probably doesn't reflect my current knowledge and beliefs.

Pages: > 1 ... 5 6 7 8 9 ... 20 >

# CppDepend

Sun
30
Sep 2012

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.

Update: CppDepend v2017 has been released recently, adding many great features, including the following:

Comments | #tools #c++ Share

# Functional Programming is the New Trend

Wed
02
May 2012

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 | #c++ Share

# Redirecting Output to File in Visual C++

Mon
16
Apr 2012

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 | #c++ #visual studio Share

# unique_ptr in Visual C++ 2010

Sat
14
Apr 2012

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 | #c++ #visual studio Share

# Iterating Backward using Unsigned Numbers

Thu
01
Mar 2012

I've had a discussion recently with my colleagues about what is the best way of writing a loop in C++ that would iterate backward: Count-1, Count-2, ..., 0, using unsigned integer numbers. I'd like to share all possible solutions I managed to gather.

Iterating forward is simple:

unsigned count = 10;
// Forward: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
for(unsigned i = 0; i < count; ++i)
    printf("%d ", i);

Iterating backward is equally simple and looks similar, if you use signed integers:

// Backward: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
// Using signed integer
for(int i = count - 1; i >= 0; --i)
    printf("%d ", i);

Same code cannot be used with unsigned integers, because it creates infinite loop, as unsigned number is always >= 0 and just wraps around to maximum value 0xFFFFFFFF:

// WRONG: Inifinte loop, unsigned int wraps around and is always >= 0.
for(unsigned i = count - 1; i >= 0; --i)
    printf("%d ", i);

Changing condition to i > 0 is also invalid, because then loop is not executed for i == 0:

// WRONG: Not executed for i == 0.
for(unsigned i = count - 1; i > 0; --i)
    printf("%d ", i);

Here comes a bunch of possible valid solutions. My favourite is following for loop:

for(unsigned i = count; i--; )
    printf("%d ", i);

Following while loop does same thing. Some people say that it looks more clear. I don't think so, while I believe the for loop is better because it creates local scope for variable i, while the following code does not:

unsigned i = count;
while(i--)
    printf("%d ", i);

Another way of implementing exactly same logic is to write the condition like this. It may look like C++ had the "goes to zero" arrow operator -->, but it is actually just (i-- > 0) :)

unsigned i = count;
while(i --> 0)
    printf("%d ", i);

Another possible solution of loop condition (a one that does not use the postdecrementation operator) is to compare i with maximum integer value. One disadvantage of it is that you have to carefully match the value of the max constant with type of your iterator - whether it is unsigned int, unsigned short etc.

for(unsigned i = count - 1; i != UINT_MAX; --i)
    printf("%d ", i);

Another way of doing this, without using maximum value, is:

for(unsigned i = count - 1; i < count; --i)
    printf("%d ", i);

Finally there are solutions possible that introduce second iterator:

// Option 1 using second iterator:
// i goes 0...9, j is inverted i.
for(unsigned i = 0; i < count; ++i)
{
    unsigned j = count - i - 1;
    printf("%d ", j);
}

// Option 2 using second iterator:
// i goes 10...1, j is decramented i.
for(unsigned i = count; i > 0; --i)
{
    unsigned j = i - 1;
    printf("%d ", j);
}

Which is your favorite loop? Please leave a comment :)

Comments | #algorithms #c++ Share

# How to Make Visual Studio Debugger not Step Into STL

Fri
10
Feb 2012

It is annoying when you debug your C++ code in Visual Studio, want to step into your function, but the debugger enters source code of some STL container or string. For example, in the following code you will first enter std::basic_string constructor, then std::vector operator[] and then body of MyFunction.

MyFunction(std::string("abc"), myVector[0]);

It turns out there is a way to disable stepping into certain code, using regular expressions. To do this:

  1. Run Registry Editor (regedit.exe).
  2. Navigate to the key appropriate to your version of Visual Studio or Visual C++. "VCExpress" is for free Visual C++ Express, while "VisualStudio" is for commercial Visual Studio. Number is product version. Additional "Wow6432Node" should be used when working in 64-bit Windows. For example:
    • Visual C++ 2005 Express in 32-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VCExpress\8.0\NativeDE\StepOver
    • Visual Studio 2005 Professional in 32-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\NativeDE\StepOver
    • Visual Studio 2008 Professional in 64-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\NativeDE\StepOver (for version 2008 it's 9.0 not 8.0, the article linked below is wrong!)
    • Visual Studio 2010 Professional in 64-bit Windows: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\10.0\NativeDE\StepOver
  3. Create new String Value with any name and a value containing regular expression to match against identifiers you want to exclude, like "std\:\:.+" for all identifiers from STL namespace (including members of std::string, std::vector and so on). I assume you know the syntax of regular expressions.
  4. In Visual up to 2008, it starts working after you start new debug session (e.g. with F5). In Visual 2010, you have to restart whole IDE.

Here is the full story:

In May 2007 I asked the question on forum.warsztat.gd and written this blog entry (in Polish). Now I've also found this article: How to Not Step Into Functions using the Visual C++ Debugger, Andy Pennell's Blog and this StackOverflow question: Is there a way to automatically avoiding stepping into certain functions in Visual Studio?

From that I've learned that Visual Studio 6.0 used autoexp.dat file, while new versions use Windows registry.

Rules entered in registry can be suffixed with case-insensitive "=NoStepInto" (which is the default) or "=StepInto".

Aside from regular expression syntax you can use additional special codes: \cid (identifier), \funct (function name), \scope (class or namespace, like myns::CClass::), \anything (any string) and \oper (C++ operator).

Double backslashes you can meet on some web pages come from the REG file format, where backslash must be additionally escaped, like "\\:". If you enter regular expression straight into regedit, it should be "\:".

NEW: In Visual Studio 2015, it is completely different. To add such entry:

  1. Open file: c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Packages\Debugger\Visualizers\default.natstepfilter
  2. To be able to modify it, you must overcome two obstacles: 1. It's in Program Files directory, so you have to do it as administrator. 2. The file is Read-Only, so you need to disable this attribute.
  3. Add following entry to this XML file: <Function><Name>std::.+</Name><Action>NoStepInto</Action></Function>

Comments | #c++ #visual studio #debugger Share

# CPrintStream - Polymorphic Printf

Thu
02
Feb 2012

Constructing and sending somewhere (like to the console or to file) a string created ("formatted") from multiple values of different types (strings, numbers) is a common task in every programming language. C implements it using printf function, which is very convenient, although not type safe. In C++ it is recommended to use streams from standard library, but they are slower, as well as much less pleasant to code comparing to the functions that use formatting string. Let's say you have a numeric variable and you want to print it as 8-digit hexadecimal value, like "0x00001234". Which option looks better?

#include <cstdlib>
#include <iostream>
#include <iomanip>

unsigned u = 0x1234;

// Option 1
printf("0x%08X\n", u);

// Option 2
std::cout << "0x" << std::setw(8) << std::setfill('0') << std::hex << u << std::endl;

I choose option 1 :) In the world of GUI applications, printing text messages may seem not so common, but sometimes it it useful, e.g. for logging debug information. Recently I thought: Why not connect the C-style printing with what is good in C++: classes and polymorphism? That's how I coded simple CPrintStream class and some derived classes, which I'd like to share here:

PrintStream.hpp
PrintStream.cpp

Abstract base class CPrintStream defines method printf(const char* format, ...) for printing a formatted message to some kind of target. Derived classes implemented this as printing to system console (CConsolePrintStream), file (CFilePrintStream) or a buffer in memory (CMemoryPrintStream).

Here are some implementation details. First problem I had to overcome was that the variable argument list ... cannot be passed from function to function. It has to be resolved to a value of type va_list using va_start and va_end functions. Fortunately this va_list object can be passed as argument to another function and all functions that take ... (like printf, fprintf) have their equivalents taking va_list (like vprintf, vfprintf). So my CPrintStream::printf method just converts ... to va_list and passes it to another method called vprintf, and only this one is pure virtual to be overriden in derived classes.

class CPrintStream {
public:
    virtual ~CPrintStream() = 0 { }
    void printf( const char* format, ... );
    virtual void vprintf( const char* format, va_list argList ) = 0;
};

CConsolePrintStream does its job using vprintf function from standard C library - the va_list equivalent of printf. CFilePrintStream uses fopen_s to open a file of type FILE* and does printing with vfprintf function - the va_list equivalent of fprintf.

Finally, the CMemoryPrintStream uses std::vector<char> as buffer for raw binary data. I believe that's the best choice as: 1. STL vector can be easily resized, 2. char is the type recommended to represent raw bytes, 3. vector stores data in continuous memory that you can safely access by writing &myVector[index], which is not guaranteed in std::string. How do I store formatted string in memory? I use vsprintf_s - the va_list equivalent of sprintf. But before this, I calculate required length with _vscprintf - a function I've learned about recently. I believe using it is much better than sprintf-ing to some buffer of constant length, e.g. char temp[1024], like many programmers do.

Update 2015-12-05: A newer version of this code is available on: GitHub sawickiap / MISC / PrintStream

Comments | #c++ Share

# Visual C++ is so Liberal

Tue
31
Jan 2012

Here is an issue in C++ code I've came across some time ago and recently I've found again in some other code. This code is invalid according to language standard, still it compiles in Visual C++/Visual Studio and works correctly. Can you see what's wrong with it?

class Class1
{
public:
    int m_Number;
    Class1( int number ) : m_Number( number ) { }
};

void Function1( Class1& obj1 )
{
    obj1.m_Number = 2;
}

int main()
{
    Function1( Class1( 1 ) );
}

The problem is that we pass a temporary object of Class1 to the Function1, while this function takes object by reference, not by reference to const. Such R-value shouldn't be converted to non-const reference, or else we could modify the temporary object - which we actually do inside the function.

Visual C++ 2008 and 2010 with default project options compiles this without any warning. Setting Warning Level to 4 (/W4) generates a warning:

warning C4239: nonstandard extension used : 'argument' : conversion from 'Class1' to 'Class1 &'

Using Disable Language Extensions (/Za) makes it an error:

error C2664: 'Function1' : cannot convert parameter 1 from 'Class1' to 'Class1 &' A non-const reference may only be bound to an lvalue

It means we are dealing with a nonstandard Microsoft extension here. GCC refuses to compile this code, even with standard options:

error: invalid initialization of non-const reference of type 'Class1&' from an rvalue of type 'Class1' error: in passing argument 1 of 'void Function1(Class1&)'

Another story: Today I've learned that C++ standard doesn't have forward declarations of enums. I used it for long time and now I know it's another nonstandard Microsoft extension.

My conclusion is that programming in C++ using Visual C++ is like programming in DirectX using NVIDIA graphics cards: the platform is so liberal that your code may work even if you do something invalid. It also means that to use portable libraries instead of WinAPI is not enought to write code portable from Windows to Linux and other platform. You should also check if your code is accepted by other compilers. Increasing warning level in project options can also help with that, just like using Debug Version of Direct3D in DiectX Control Panel and observing debugger Output to find possible problems in calls to Direct3D API. It's better to ensure early that your code is valid instead of later complain that alternative (GCC) compiler or alternative (AMD) GPU driver causes problems.

On the other hand I believe that platform independence and strict C++ standard correctness is not a great value in itself. If you know your code is supposed to just work under Windows and be compiled in Visual C++, why not make use of available extensions and rely on specific compiler behavior? It can be convenient, while maintaining code that have to work with different compilers and platforms is a lot of additional work, possibly unnecesary.

Comments | #c++ #visual studio Share

Pages: > 1 ... 5 6 7 8 9 ... 20 >

[Download] [Dropbox] [pub] [Mirror] [Privacy policy]
Copyright © 2004-2026