2012-06-27 16 views
21

Así que, básicamente este código:¿Por qué se llama al constructor de copia en lugar del constructor de conversión?

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 
} 

sólo genera un error de B b2 = a. Y ese error es

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

¿Por qué está intentando llamar al constructor de copia además del constructor de conversión directa?

Está claro en el mensaje de error que se crea un B temporal que luego se utiliza para la construcción de copias, pero ¿por qué? ¿Dónde está esto en el estándar?

+0

Es su pregunta está relacionada, por casualidad, con [este] (http://stackoverflow.com/questions/11221242/is-this-a-copy-constructor)? :) –

+0

@EitanT ¿Cómo lo sabes? –

+0

Porque revisé esa pregunta hace unos minutos :) –

Respuesta

13
B b2 = a; 

Esto se conoce como Copy Initialization.

Lo hace thh siguiente:

  1. crear un objeto de tipo B de a utilizando B (const A& a).
  2. Copie el objeto temporal creado a b2 utilizando B (const B& b).
  3. Destruye el objeto temporal usando ~B().

El error que se obtiene no es en el paso 1, sino más bien en el paso 2.

Where is this in the standard?

C++ 8.5 03 Inicializadores
Párrafo 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

¿Pero por qué no usar directamente el constructor de conversiones? –

+0

@LuchianGrigore: Sí. El error es * después * de que la conversión se haya realizado durante la construcción de la copia. La llamada al constructor de copia también podría ser eliminada, pero eso depende de la compilación. Además, el constructor de copia debe ser accesible. –

+0

Sí, lo tengo (y sé que tienen que ser visibles independientemente de si se llaman o no). ¿Pero por qué no solo lo hace en un solo paso? ¿Por qué la necesidad de una 'B' temporal? –

Cuestiones relacionadas