2012-06-27 15 views
21

Więc w zasadzie ten kod:Dlaczego zamiast konstruktora konwersji wywoływany jest konstruktor kopiowania?

class A { 
}; 
class B { 
    B (const B& b) {} 
public: 
    B(){} 
    B (const A& a) {} 
}; 

int main() 
{ 
    A a; 
    B b1(a); //OK 
    B b2 = a; //Error 
} 

generuje tylko błąd na B b2 = a. I ten błąd jest

error: ‘B::B(const B&)’ is private

Dlaczego próbuje wywołać konstruktora kopiowania oprócz bezpośredniego konstruktora konwersji?

Z komunikatu o błędzie wynika, że ​​został utworzony tymczasowy kod B, który jest następnie używany do tworzenia kopii, ale dlaczego? Gdzie to jest w standardzie?

+0

Czy twoje pytanie związane, przez przypadek, do [tego] (http://stackoverflow.com/questions/11221242/is-this-a-copy-constructor)? :) –

+0

@EitanT Skąd wiedziałeś? –

+0

Ponieważ sprawdziłem to pytanie kilka minut temu :) –

Odpowiedz

13
B b2 = a; 

ten jest znany jako Copy Initialization.

Czyni thh następujący:

  1. Tworzenie obiektu typu B z a za pomocą B (const A& a).
  2. Skopiuj utworzony obiekt tymczasowy do b2, używając B (const B& b).
  3. Zniszcz tymczasowy obiekt przy użyciu ~B().

Błąd można dostać nie jest w punkcie 1, lecz w kroku 2.

Where is this in the standard?

C++ 03 8.5 inicjalizatory
Para 14:

....
— If the destination type is a (possibly cv-qualified) class type:
...
...
— Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the destination type. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8.

+1

Ale dlaczego nie użyć bezpośrednio konstruktora konwersji? –

+0

@LuchianGrigore: To robi. Błąd jest * po * konwersja została wykonana, podczas kopiowania konstrukcji.Związanie do kopiowania konstruktora może również zostać usunięte, ale to zależy od kompilatora.Również nadal konstruktor kopiowania musi być dostępny. –

+0

Tak, mam to (i wiem, że muszą być widoczne niezależnie od tego, czy są wywoływane, czy nie). Ale dlaczego nie robi tego po prostu w jednym kroku? Dlaczego potrzeba tymczasowego 'B'? –

Powiązane problemy