15 Nisan 2019 Pazartesi

std::size_t tipi - unsigned

Giriş
size_t hem C hem de C++ standartlarında var. C++'ta std::size_t olarak tanımlı.

C için şu satırı dahil ederiz.
#include <stdint.h>  /* SIZE_MAX */
C++ için şu satırı dahil ederiz.
#include <cstddef>
C++ hem global hem de std isim alanları içinde tanımlama yapar. Açıklaması şöyle.
C-style header names like <stddef.h> are deprecated. However, C++-style headers like <cstddef> are allowed to declare their names in global namespace and then redeclare the same names in namespace std through using-declarations
std::size_t unsigned bir tiptir
size_t unsigned bir değer döner. Örneğin bir çok veri yapısının count() metodu size_t döner. unsigned değer 0 ise, 0'dan 1 çıkartmak -1 yerine başka bir sonuç verir. Bu durum bir sürü hataya sebep oluyor. Signed/Unsigned Integer Karışımı yazısına bakabilirsini.z

SIZE_MAX
size_t'nin alabileceği en büyük değeri temsil ederi. Bu değerin ne olacağı belirsiz. Ancak en az ne olması gerektiği belli. Açıklaması şöyle.
size_t is specified to be a standard unsigned integer, but the standard does not restrict its size relative to any of them other than by saying that it must be able to hold at least 65535.
Bu değer ile calloc arasında da bağlantı var.
( size_t - 1) değeri SIZE_MAX ile temsil edilir. Bu değer gcc'de şöyle tanımlı. 64 bit için bayağı büyük bir rakam verilmiş.
/* Limit of `size_t' type.  */
# if __WORDSIZE == 64
#  define SIZE_MAX              (18446744073709551615UL)
# else
#  define SIZE_MAX              (4294967295U)
# endif
size_t ve int ilişkisi
size_t int'ten daha büyük veya daha küçük olacak diye hiçbir ilişki tanımlı değil. Açıklaması şöyle.
The current C standard does not require size_t to be at least as wide as an int, and I'm skeptical about any version of the standard ever doing so. size_t needs to be able to represent any number which might be the size of an object; if the implementation limits object sizes to be 24 bits wide, then size_t could be a 24-bit unsigned type, regardless of what an int is.
int yerine size_t
int yerine size_t kullanmak zorunda değiliz. Açıklaması şöyle.
size_t is an unsigned integer that is capable of holding the size of the largest object you can allocate. It is useful for indexing because this means it can index into the largest array you can allocate.

This does not mean it is required or even necessarily recommended for indexing. You can use any integer type that is large enough to index the array. int_fast32_t might be faster, uint_least16_t might be smaller in a structure, and so on. Know your data, and you can make a good choice.

Ancak bence int yerine size_t kullanmak daha iyi. Eskiden şöyle yapardık.
double get(const double* p, int k) {
  return p[k];
}
Şimdi şöyle yaparız.
double get(const double* p, size_t k) {
  return p[k];
}

11 Nisan 2019 Perşembe

Constructor İçinde Exception Fırlatmak

Giriş
Eğer bir nesnenin costructor metodu içinde exception atılırsa, o nesnenin destructor metodu çağrılmaz. Açıklaması şöyle.
C++11 15.2 Constructors and destructors (2)
An object of any storage duration whose initialization or destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution.
1. Destructor'ımın Çağrılmaması
Örnek
Elimizde şöyle bir kod olsun. Holder sınıfı ve bu sınıfın içinde yaşayan başka bir sınıf var.
class Object
{
public:
  Object() { std::cout << "Object() ctor" << std::endl; }
  ~Object() { std::cout << "~Object() dtor" << std::endl; }
};

class Holder
{

public:
  Holder() :myObjectP( new Object() )
  {
    throw std::exception();
  }
  ~Holder()
  {
    std::cout << "~Holder()" << std::endl;
    delete myObjectP;
  }
private:
  Object* myObjectP;

};
Bu sınıfı kullanmak için şöyle yaparız.
int main(int argc, char* argv[])
{
  try
  {
    std::cout << "begin try" << std::endl;
    Holder h;
  }
  catch ( ... )
  {
    std::cout << "begin catch" << std::endl;
  }
  return 0;
}
Holder nesnesi constructor metodu içinde exception attığı için destructor metodu çağrılmıyor. Dolayısıyla içindeki pointer Object nesnesi de silinmiyor. Çıktı olarak şunu alırız.
begin try
Object() ctor
begin catch
2. New Kullanırken Constructor İçinden Exception Fırlatmak
new memory leak'e sebep olmaz. Açıklaması şöyle.
Whenever the constructor of MyClass throws, new MyClass(); does not produce any memory leak since the storage allocated for MyClass is automatically freed by new when an exception is thrown.
Açıklaması şöyle.
If the new-expression creates an object or an array of objects of class type, access and ambiguity control are done for the allocation function, the deallocation function, and the constructor. If the new-expression creates an array of objects of class type, the destructor is potentially invoked.
Açıklaması şöyle.
If construction of any object in the buffer throws an exception, the previously constructed objects must be destructed. That requires an available destructor.
Örnek
Elimizde şöyle bir kod olsun. Bu kod memory leak'e sebep olmaz.
MyClass* MyClass::getNewMyClassInstance()
{
    return new MyClass();
}
Örnek
Elimizde şöyle bir kod olsun.
int counter;

class Destruct
{
public:
  Destruct()
  {
    if (counter++ > 5)
      throw counter;
  }

  ~Destruct()
  {
    std::cout << "Dtor called\n";
  }
};

int main()
{
  try
  {
    new Destruct[10];
  }
  catch (...){}
}
Çıktı şunu alırız. Burada 7 nesne yaratılıken exception fırlatılıyor. Fully constucted 6 nesne için destructor çağrılıyor.
Dtor called
Dtor called
Dtor called
Dtor called
Dtor called
Dtor called

10 Nisan 2019 Çarşamba

IEEE 754 ve İki Sayının Eşitliği

Giriş
Yöntemler şöyle
1. Her sayı belli bir küsurat hanesine yuvarlanır ve >, < işlemine sokulur.
2. Epsilon veya diğer ismiyle tolerans değeri kullanılarak karşılaştırma yapılır.

3. Belirtilen ULP (x ve y değeri arassındaki kaç tane double olduğu) kadar yakın olup olmadığının karşılaştırması yapılır.

Mutlak Epsilon'a Göre Karşılaştırmak
Açıklaması şöyle. x ve y küçük sayılar iken kullanışlı. Burada sadece tek bir epsilon aralığına bakılıyor.
For numbers between 1.0 and 2.0 FLT_EPSILON represents the difference between adjacent floats. For numbers smaller than 1.0 an epsilon of FLT_EPSILON quickly becomes too large, and with small enough numbers FLT_EPSILON may be bigger than the numbers you are comparing (a variant of this led to a flaky Chromium test)!

For numbers larger than 2.0 the gap between floats grows larger and if you compare floats using FLT_EPSILON then you are just doing a more-expensive and less-obvious equality check. That is, if two floats greater than 2.0 are not the same then their difference is guaranteed to be greater than FLT_EPSILON. For numbers above 16777216 the appropriate epsilon to use for floats is actually greater than one, and a comparison using FLT_EPSILON just makes you look foolish. We don’t want that.
Örnek
Şöyle yaparız.
bool absoluteToleranceCompare(double x, double y)
{
  return std::fabs(x - y) <= std::numeric_limits<double>::epsilon() ;
}
Relative Epsilon'a Göre Karşılaştırmak
Açıklaması şöyle. x ve y büyük sayılar ilen kullanışlı. Burada daha fazla büyük epsilon aralığına bakılıyor.
The idea of a relative epsilon comparison is to find the difference between the two numbers, and see how big it is compared  to their magnitudes. In order to get consistent results you should always compare the difference to the larger of the two numbers. In English:

To compare f1 and f2 calculate diff = fabs(f1-f2). If diff is smaller than n% of max(abs(f1),abs(f2)) then f1 and f2 can be considered equal.
Epsilon şöyle hesaplanır.
double Epsilon = std::max(x, y) * std::numeric_limits<double>::epsilon();
Örnek
Şöyle yaparız. Yukarıdaki Epsilon hesaplamadan farklı olarak x ve y'nin mutlak değerinin max()'ı alınıyor. Fark yaratır mı bilmiyorum.
bool relativeToleranceCompare(double x, double y)
{
  double maxXY = std::max( std::fabs(x) , std::fabs(y) ) ;
  return std::fabs(x - y) <= std::numeric_limits<double>::epsilon()*maxXY ;
}
Eğer her iki örneği birleştirmek istersek şöyle yaparız
bool combinedToleranceCompare(double x, double y)
{
  double maxXYOne = std::max( { 1.0, std::fabs(x) , std::fabs(y) } ) ;

  return std::fabs(x - y) <= std::numeric_limits<double>::epsilon()*maxXYOne ;
}
Örnek
The art of computer programming by Knuth kitabındaki örnekler şöyle. approximatelyEqual() metodu relativeToleranceCompare() metodu ile aynı. essentiallyEqual() metodunu anlamadım.
bool approximatelyEqual(float a, float b, float epsilon)
{
  return fabs(a - b) <= ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

bool essentiallyEqual(float a, float b, float epsilon)
{
  return fabs(a - b) <= ( (fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

bool definitelyGreaterThan(float a, float b, float epsilon)
{
  return (a - b) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}

bool definitelyLessThan(float a, float b, float epsilon)
{
  return (b - a) > ( (fabs(a) < fabs(b) ? fabs(b) : fabs(a)) * epsilon);
}
ULP'ye Göre Karşılaştırmak
Açıklaması şöyle.
We already know that adjacent floats have integer representations that are adjacent. This means that if we subtract the integer representations of two numbers then the difference tells us how far apart the numbers are in float space. 
Yani
In other words, if you subtract the integer representations and get one, then the two floats are as close as they can be without being equal. If you get two then they are still really close, with just one float between them. The difference between the integer representations tells us how many Units in the Last Place the numbers differ by. This is usually shortened to ULP, as in “these two floats differ by two ULPs.”
Şöyle yaparız.
// Usable AlmostEqual function    
bool AlmostEqual2sComplement(float A, float B, int maxUlps)    
{    
    // Make sure maxUlps is non-negative and small enough that the    
    // default NAN won't compare as equal to anything.    
    assert(maxUlps > 0 && maxUlps < 4 * 1024 * 1024);    
    int aInt = *(int*)&A;    
    // Make aInt lexicographically ordered as a twos-complement int    
    if (aInt < 0)    
        aInt = 0x80000000 - aInt;    
    // Make bInt lexicographically ordered as a twos-complement int    
    int bInt = *(int*)&B;    
    if (bInt < 0)    
        bInt = 0x80000000 - bInt;    
    int intDiff = abs(aInt - bInt);    
    if (intDiff <= maxUlps)    
        return true;    
    return false;    
}