Etiquetas

12/09/2014

C++: consts and const references and const pointers and const methods, oh my!

C++ is powerful. But it has some concepts that seem easy to understand... until you actually use them for the first time. This is a compilation of some of my head-scratching moments while grasping C++ capabilities that are foreign to C programmers like me.

References

Declare a variable with "&" and it is a reference. Think of a C pointer ("*"), but it can not be NULL and you can not cast it to reference another type (the case of C's malloc() returned void pointer). Examples:
    // With a basic type
    int number = 3;
    int &reference = number;
    cout << reference << endl; // Prints 3
    reference = 1;
    cout << number << endl; // Now it prints 1

    // With a class instance
    string stringInstance = "Hi!";
    string &stringReference = stringInstance;
    cout << stringReference.size() << endl; // Note we are not using the "->"
                                            //  operator! It is not a pointer.
References in method declarations allow you to pass the instance itself instead of the value
/* Reverse a string in place, avoiding copies */
void reverse(string input){
    for (int i = 0, j = input.size() - 1; i < j; ++i, --j){
        char tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
    }
}
That didn't do anything to the real "input" string. This is C++, so "input" is an instance of the class "string" and not a pointer. The method reverse() has been working on a copy of the class instance that was destroyed as soon as the method finished! Solution? We could pass a pointer (string *input) and go crazy like in C, but then we would have to check for NULL pointers, use the "->" operator and who knows what else. The C++ way? Use a reference!
/* Reverse a string in place, avoiding copies */
void reverse(string &input){
    for (int i = 0, j = input.size() - 1; i < j; ++i, --j){
        char tmp = input[i];
        input[i] = input[j];
        input[j] = tmp;
    }
}
No changes required to the method body. It is also required for optimization, cause it avoids a deep copy of the instance's internal structure.

Const

The qualifier "const" (which also exists in C) can be mostly read as "readonly" (think Java's "final"). It effects whatever is on its left. If there is nothing on its left, then it effects the first thing on its right. So this is a mistake:
const int const *p = ...; // Compiler error, duplicate const!
Now the caveats:
    const int number = 2; // int value is readonly now
    int &reference = number; // Compiler error: "int &" requires
                             // an "int", not a "const int"
Fix:
    const int number = 2;
    const int &reference = number; // But now "reference = 1;" is an error, careful!
Note that "const int & reference" and "int const & reference" is the same thing (remember, left unless there's nothing, if so, right). What if we start moving the const modifier around?
   int & const reference = number; // Compiler error: const attempts
                                    // to modify the reference itself (&),
                                    // but references are always readonly!

Const and pointers

A C refresher. Remember: const affects that on its left, including the pointer (*) itself.
    // With a basic type
    int number = 2;
    const int *p = &number;
    *p = 3;   // Compiler error: the value is readonly!
    int * const pp = &number;
    *pp = 3;    // OK
    pp = &argc; // Compiler error, the pointer is readonly!

Const and method declarations

Const applies also to method arguments:
void clearString(const string & input){
    cout << "Deleting this many characters: " << input.size() << endl;
    input.clear();  // Compiler error: the instance is readonly!
}
Wait... how did the C++ compiler know the method clear() would change the string, and size() wouldn't? Hardcore static code analysis? AI? Magic? Not really. Const has another use: specifying which member methods in a class change no values and hence are safe to be called when the class is readonly. This is the declaration of the size() method in string, note the const after the parenthesis:
// Capacity:
///  Returns the number of characters in the string, not including any
///  null-termination.
size_type size() const
{
    return _M_rep()->_M_length;
}
That use of const is exclusive to objects. It will throw a compiler error if you try to use it in a function declaration that does not belong to a class.

Done for today. Hope it helped you!

2/18/2011

1 libro 1 euro

Ya escribí acerca de la iniciativa de donar un euro a Save the Children a cambio del libro "Espía de Dios" para descarga gratuita. Ahora esa iniciativa se ha oficializado con una página web solidaria donde están disponibles estos tres libros:
  • El ya mencionado Espía de Dios, por Juán Gómez-Jurado
  • La ya publicada en internet Realidad Aumentada, por Bruno Nievas
  • Apocalipsis Z, por Manuel Loureiro
Próximamente se agregarán más libros a la lista, para gozo por parte de la ONG Save the Children.

Una curiosa pero exitosa consecuencia del hartazgo ante el mamoneo y demagogia de los defensores de la industria audiovisual española.

2/08/2011

Gracias al hipócrita de Alejandro Sanz, novela "Espia de Dios" gratis y más ayuda a África

Coincidencias cósmicas. ¿Recordáis que escribí sobre una novela para descarga gratuita por Bruno Nievas? ¿Y que cité cómo Juan Gómez-Jurado, escritor superventas, apoyó y recomendó esa novela?

Pues de alguna manera todo eso se ha juntado con la hipocresía de Alejandro Sanz para proporcionar un momento de puro humor.

Podéis leer el episodio completo en el blog Esperanza y Constancia, de donde me he enterado.

2/07/2011

El primer día en el trabajo del carretillero Klaus

Parece increible, pero se puede hacer un video sobre un carretillero bastante divertido y ganador de seis premios al mejor corto.

Desarrollo con Qt en Nokia 5800 XpressMusic (2): configurar el entorno de desarrollo

Continúo con el desarrollo para Nokia 5800. Anteriormente hablé un poco de la historia y estado actual ("state of the art" que dirían los yanquis) del desarrollo para dispositivos Nokia.

Ahora empiezo la parte práctica con la configuración inicial del entorno de desarrollo y la ejecución de un ejemplo incluido en el entorno de desarrollo Qt Creator. Usaremos ahora el emulador, más adelante probaremos la ejecución directa en el móvil tras configurarlo.

2/03/2011

Scammer sells Blender

From Blender Nation:

With the success of blender.org projects, and publishing all the exciting Blender releases, we’re now being challenged by third parties who like to ride the waves and do business with Blender.

There’s nothing wrong with that. In its very nature, GNU GPL is about freedom, the freedom not only to use and modify the sources, but also to distribute and resell our releases under another brand name.

Recently we received several concerned emails and forum postings from people who were worried about Blender resellers using especially Ebay to sell Blender.

In this case, the products 3DMagix and IllusionMage are just rebranded Blender material, sold at a price with lots of wrong info. And even more, they use copyrighted images with no authorization, including pictures like a render of a Final Fantasy X character!

And helping here as it's asked in the Blender Nation article:

3DMagix, 3DMagixPro, IllusionMage, scam

1/30/2011

LibreOffice Portable: distribución para USB

La Document Foundation ha anunciado el lanzamiento de LibreOffice Portable. Se trata de una versión de la suite de ofimática LibreOffice para Windows que se ejecuta desde un USB sin necesidad de instalación.

Vodafone lleva al juzgado a una niña de siete años por 700 euros

Vía Meneame:
Una compañía telefónica lleva al juzgado a una niña de siete años de es Pil·larí por 700 euros
Dos cosas:
  1. Me parto.
  2. No quiero trabajar como responsable de imagen de Vodafone.

1/29/2011

Pediatra almeriense ofrece gratis novela, consigue más de 7 mil descargas

Bruno Nievas, pediatra de profesión, no ha conseguido encontrar editor para su novela "Realidad Aumentada", un thriller tecnológico. Por ello lo ha puesto en internet para su descarga gratuita. Ahora mismo lleva más de 7.800 descargas.

Razones para NUNCA confiarse con las tiendas de operadores

Vía Meneame: Vodafone reclama 570 euros por cambio de titularidad en línea ADSL.

Bien, ya antes avisé de los problemas con los comerciales de Vodafone. En este caso la situación se produce en una tienda y es: