2010-04-01 18 views

cevap

7

:

öncelikle şablonları işlev referanslar "besleme" için kullanılan tipi T bir nesne için bir başvuru içeren boost :: reference_wrapper amacı Parametrelerini değerini alarak alan (algoritmalar).

Not: boost::reference_wrapper ve std::reference_wrapper arasındaki önemli bir fark (Boost 1.52 en az), mükemmel işlevi, nesne sarmak için std::reference_wrapper yeteneğidir.

Bu, böyle bir kod sağlar:

örneğin Boost.Thread olarak
// functor that counts how often it was applied 
struct counting_plus { 
    counting_plus() : applications(0) {} 
    int applications; 

    int operator()(const int& x, const int& y) 
    { ++applications; return x + y; } 
}; 

std::vector<int> x = {1, 2, 3}, y = {1, 2, 3}, result; 
counting_plus f; 
std::transform(begin(x), end(x), begin(y), 
       std::back_inserter(result), std::ref(f)); 
std::cout << "counting_plus has been applied " << f.applications 
      << " times." << '\n'; 
+0

@Venkat Shiva: durum ve "algoritmalar değeriyle kendi parametresi alması gerektiğinde" Sen değeriyle bir nesne geçme performans kaybına yol istemiyoruz olduğunu . –

+0

Soruları göndermeden önce belgeleri doğru şekilde okumalıyım. Sorun için üzgünüm. –

4

:

yeni bir iplik herhangi bir parametre ile çağrılan olabilir bir çağrılabilir tipte bir nesne geçirilmesiyle başlatılan

yapıcısına. Nesne daha sonra iç depolama birimine kopyalanır ve yeni oluşturulmuş iş parçacığı 'da çağrılır. Nesnenin kopyalanmaması (veya gerçekleştirilememesi) durumunda, boost :: ref, nesnesinin nesnesinin bir işlevine başvurmak için kullanılabilir. Bu durumda, Boost.Thread kullanıcısı, atıfta bulunulan nesnenin, yeni oluşturulmuş iş parçacığı 'u aşmasını sağlamalıdır. dokümandan

Kodu:

struct callable 
{ 
    void operator()(); 
}; 

boost::thread copies_are_safe() 
{ 
    callable x; 
    return boost::thread(x); 
} // x is destroyed, but the newly-created thread has a copy, so this is OK 

boost::thread oops() 
{ 
    callable x; 
    return boost::thread(boost::ref(x)); 
} // x is destroyed, but the newly-created thread still has a reference 
    // this leads to undefined behaviour