📜 ⬆️ ⬇️

C ++ 0x and initialization problem solving

C ++ 0x In articles on Habré already concerned standard C ++ 0x, and in particular lambda expressions. I wanted to write more about a couple of changes and additions that will be made in C ++. And without further ado to the case.


Initializing Integer Variables


C ++ 0x solves the problem of casting elementary integer types to integer ones. In the simplest example, it looks like this:

Classic C ++:
')
int a = 7.3; // int
void func( int );
func(5.6); //



In C ++ 0x, the problem is solved by introducing a new construct for {}:

int x1 = {7.3}; // -
double d = 7;
int x2 {d}; // ,
char x3{7}; //
vector< int > vi = { 1, 2.3, 4, 5.6 }; // ,



Delegation of designers


In C ++, you must have two constructors to perform almost the same actions or use an additional function.

Classic C ++:

class X
{
int a;
validate( int x)
{
if (0<x && x<=max) a=x;
else throw bad_X(x);
}

public :
X( int x) // int
{
validate(x);
}

X() // -
{
validate(42);
}

X( string s) // string
{
int x = lexical_cast< int >(s);
validate(x);
}
// ...
};



In C ++ 0x, one constructor can be declared in the context of another constructor:

class X
{
int a;

public :

X( int x) // int
{
if (0<x && x<=max) a=x;
else throw bad_X(x);
}

X() :X{42} { } // -

X( string s) :X{lexical_cast< int >(s)} { } // string

// ...
}



Null pointers



In the standard C ++, the null pointer is the usual 0. In the libraries, one can find #define NULL 0. In ++ 0x, the special literal nullptr is introduced.

Example of use:

char * p = nullptr;
int * q = nullptr;
char * p2 = 0; // -

void f( int ); // int
void f( char *); // char*

f(0); // f(int) -
f(nullptr); // f(char*) -

void g( int );
g(nullptr); //: nullptr int
int i = nullptr; //



Conclusion


The changes, of course, are a bit cosmetic, but they make the language safer and more convenient, and most importantly, they don’t look as extreme as lambda expressions).

To be continued…

Progg it

Source: https://habr.com/ru/post/69313/


All Articles