Tag: visual studio

Entries for tag "visual studio", ordered from most recent. Entry count: 50.

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

Pages: > 1 2 3 4 ... 7 >

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 (18) | Tags: c++ visual studio | Author: Adam Sawicki | Share

22:49
Fri
10
Feb 2012

How to Make Visual Studio Debugger not Step Into STL

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 "\:".

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

22:53
Tue
31
Jan 2012

Visual C++ is so Liberal

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 (0) | Tags: c++ visual studio | Author: Adam Sawicki | Share

22:45
Thu
15
Sep 2011

Windows 8 Developer Preview

News about upcoming Windows 8 appear for some time. Information about the new Windows version directly from Microsoft, including technical details for developers, can be found in this PDF: Windows Developer Preview - Windows 8 guide. Recently Microsoft shared a full, development version of this system to download, install and test on your computer for free. It's a developer preview - it contains the new operating system along with new Visual Studio 11. You can download it as ISO image from Windows Developer Preview downloads. The system works in VirtualBox virtual machine. You can see my first gallery of screenshots here:

My first impressions after testing Windows 8 are... quite weird. Apparently they try to make desktop OS looking like a cellphone, with big fonts and all apps working in fullscreen. But that's only a half-truth. I feel that in Microsoft they always do it this way: a boss comes and tells that "we do it again from scratch only better, redefine everything, but we have to preserve backward compatibility", then a developer thinks how to implement it the simplest possible way and it ends in a new flashy UI containing several shortcuts to the most important commands with the old, good windows hiding somewhere under "Advanced" button. It was the same with Control Panel, with formatting functions in MS Office and now it's the same with the whole Desktop. You are presented a new screen full of colourful rectangles, but as soon as you move your cursor to the bottom-left corner of the screen and click "Start", you are teleported to the normal desktop with a wallpaper, taskbar and the Recycle Bin :)

Other things that attracted my attention: You now login to Windows using your Windows Live ID account. System is integrated with Facebook by providing some application to browse it. Explorer now uses the new Ribbon toolbar, just like new versions of MS Office, Paint or WordPad do for some time. There are lots of new games. New Task Manager is great because it now shows four columns with all most important statistics of every running program: the usage of CPU time, RAM memory, disk transfer and network transfer. Finally the new UI style: flat, colourful, minimalistic, full of solid filled rectangles.

Comments (5) | Tags: windows visual studio gui | Author: Adam Sawicki | Share

19:05
Fri
15
Apr 2011

Documentation in Visual CPP

Beginner programmers use only tutorials and are afraid of original documentation of any library. Most of programmers I know who use Visual C++ - even advanced ones - search for functions and classes documentation in Google, always being pointed to online version of MSDN Library. That's probably why noone told me about new Visual Studio documentation for such a long time.

But I can't imagine coding without having documentation for every library I use installed offline in my system and opened most of the time. For WinAPI, .NET, C and C++ standard libraries I used MSDN Library for Visual Studio 2008 SP1 - a free application that is available for download from Microsoft website in form of a DVD ISO image. But it's a 2008 version. I checked for some new version many times and couldn't find one.

Now I know that Microsoft changed this offline MSDN Library to a new help available in Visual Studio 2010, including Express edition. It can be installed by selecting Help / Manage Help Settings. A dialog box allows you to install, remove and update different parts of huge library (mine takes 3 GB of hard disk and it's located in C:\Users\All Users\Microsoft\HelpLibrary)

Files are downloaded, installed and after that, you can use Microsoft Help Viewer 1.1 to browse this documentation - hierarchical Contents, flat Index (I think it's the most useful), Favorites and full-text search. This help browser works faster than the old one (from MSDN Library). I recommend this method to anyone who code in Visual C++/C#/whatever.


Comments (8) | Tags: visual studio | Author: Adam Sawicki | Share

18:35
Tue
12
Apr 2011

Pointing to DLL Files in Visual CPP

When coding in Visual C++, we sometimes need to use some DLL libraries like FMOD, wxWidgets, Intel TBB etc. We download or build the library, setup directories to include and library files, finally #include <header.h>, #pragma comment(lib, "library.lib"), compile, run and...

Certainly our program also needs DLL file at runtime. Sure we have to attach it to the program when we distribute it, but do we really need to copy all these libraries to the Debug and Release subdirectories in our project? For a project run from Visual C++ to find required DLL files, they must be placed either in:

or in the PATH environmental variable. That's an option I've discovered yesterday. To use it in Visual C++, navigate to project properties / Configuration Properties / Debugging / Environment and set it to something like: PATH=$(PATH)$;C:\my_libraries\library_1\DLL_dir

If you do it correctly, your program launched from Visual C++ (with or without debugger - F5 or Ctrl+F5) will now be able to find required DLL libraries without need to copy them to your project directory.

Comments (8) | Tags: windows c++ visual studio | Author: Adam Sawicki | Share

19:42
Sat
12
Mar 2011

Static C++ Code Analysis with PVS-Studio

By the courtesy of its authors, I have a chance to evaluate PVS-Studio - a static code analyzer for C, C++ and C++0x. This commercial application is installed as a plugin in Visual Studio 2005/2008/2010. Fortunately I have Visual Studio 2008 Professional at home so I could try it with the code of my personal projects. PVS-Studio differs from other tools of this kind, like free Cppcheck, by finding three types of errors or warnings: general, related to OpenMP and 64-bit portability issues.

After opening my solution in Visual Studio, I choose a command from the special menu to analyze all the code.

A progressbar appears while PVS-Studio does the computations, utilizing almost 100% of all 4 CPU cores. Finally, a dockable panel appears with a list of found issues.

The general category warns about exact float comparison with == and stuff like that. It managed to find few places where I forgot the "&" character while passing a vector as const refefence parameter, rightly telling that it will cause "decreased performance". But its greatest find in my CommonLib library code was this unbelievable bug:

Some messages look funny. Should I code some general, abstract, portable, object-oriented, Alexandrescu-style template-based solution here just to avoid copying some code into several similar instructions? :)

I didn't check how the OpenMP validation works because I don't currently use this extension. As for 64-bit compatibility issues, I have lots of them - just because my code is not prepared to be compiled as 64-bit. PVS-Studio seem to do a good job pointing to places where fixed-length 32-bit integers are mixed with pointers, array indexing etc.

Overall, PVS-Studio looks like a good tool for C++ programmers who care about the quality of their code. Finding issues related to OpenMP and 64-bit compatibility can be something of a great value, if only you need such features.

Too bad that PVS-Studio, opposite to Cppcheck, is a Visual Studio plugin, not a standalone application, so it obviously requires you to have a commercial MSVS version and do not work with Express edition. But this is understandable - if you need OpenMP or 64-bit, you probably already use Visual Studio Professional or higher.

PVS-Studio analyzes C, C++ and C++0x. It doesn't work with C++/CLI language, but that's not a big flaw too. I use C++/CLI at work, but I can see it's quite unpopular, niche language. Its compilation or analysis would also be very difficult because it mixes all features from both native C++ and .NET. Even Microsoft didn't find resources to implement IntelliSense for C++/CLI in Visual Studio 2010.

Comments (23) | Tags: software engineering c++ tools visual studio | Author: Adam Sawicki | Share

20:14
Fri
11
Mar 2011

Visual Studio 2010 Service Pack 1 Released Yesterday

Yesterday Microsoft publicly released Visual Studio 2010 Service Pack 1. It is big (1.48 GB) and the installation takes quite long. It applies to all Visual Studio 2010 versions and components, including C++ Express, C# Express etc. Here is the list of changes and here is download link (you can find link to ISO file with offline installer at the bottom of that page). There are lots of fixes and improvements, but most of them apply to managed or web technologies like Silverlight. What's interesting for a C++ programmer is the addition of intrinsics to enable the extensions on the AMD and Intel new microprocessors that will be released next year - Intel AVX and AMD Bulldozer. Microsoft also claims to optimize and fix C++ compiler. Changelist mentions fixing lots of IDE crashes, including incompatibility with AMD CodeAnalyst.

Overall I think the new SP1 for VS2010 is worth installing, unless you have "Windows SDK for Windows 7 and .NET Framework 4" installed in your system. In that case an unsolved issue would happen so you should NOT install the Service Pack.

By the way: MSDN Library - the extensive documentation of C, C++, WinAPI, OpenGL, .NET and lots of other technologies - is available for free in form of an offline application for some time, but the latest version is MSDN Library for Visual Studio 2008 SP1. Do you know how to download some newer release? Or maybe that "Windows SDK" ships with it?

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

Pages: > 1 2 3 4 ... 7 >

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