Avoiding Unnecessary Object Construction (C++)

Avoiding Unnecessary Object Construction
One way to avoid unnecessary object construction is to use a reference instead of an object to store the unnamed temporary object returned by value.

This tip references both Scott Meyers' Effective C++ Item 23 ("Don't try to return a reference when you must return an object.") and Item 20 ("Facilitate the return value optimization.").

Here's the code:


const Rational& operator*(const Rational& lhs, const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

Rational a(1, 2);
Rational b(3, 5);
Rational c = a*b; // This incurs an additional object construction.

[const] Rational& c = a*b;
// A better way of doing it. Here we just give the returned temporary object a name 'c'.

Converting Numbers to Strings C++

Converting Numbers to Strings
Instead of writing your own function to convert an integer or float to a string, just use the C++ class stringstream (in the sstream header).

In C++:


#include
#include
#include
using namespace std;

void itoa(int num, string & result)
{
stringstream converter;
converter << result=" converter.str();">

Nested Functions in C++

Nested Functions in C++
Although C++ does not allow nested function declaration, you can simulate it using a structure with a static function:


void outer()
{
static int v1 = 5;
int v2 = 5;

struct thru
{
static void inner()
{
std::cout <<>

The inner() function will not have access to local variables of outer() (the line that is commented out in the code above will cause an error, for example); however, it will be able to access the local static variable v1 in outer().

3D Sample Applications

Version Compatibility: Visual Basic 5 Visual Basic 6

More information: This .zip file contains three applications which illustrate the basics of rendering 3D images using VB's graphics methods. A readme file explaining the underlying logic is included.




This code has been viewed 140303 times.

Instructions: Click the link below to download the code. Select 'Save' from the IE popup dialog. Once downloaded, open the .zip file from your local drive using WinZip or a comparable program to view the contents.

code/3Dprogramming.zip

EPaint - Complete Photo/Image Editor

Version Compatibility: Visual Basic 6

More information: EPaint is a complete photo/image editing program with a lot of great tools and the possibility for making your own filters on the fly.

This code has been viewed 72702 times.

Instructions: Click the link below to download the code. Select 'Save' from the IE popup dialog. Once downloaded, open the .zip file from your local drive using WinZip or a comparable program to view the contents.

source/epaint.zip