2012-06-27 19 views
21

तो मूल रूप से इस कोड:रूपांतरण निर्माता के बजाय कॉपी कन्स्ट्रक्टर क्यों कहा जाता है?

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 
} 

केवल B b2 = a के लिए एक त्रुटि उत्पन्न करता है। और उस त्रुटि है

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

क्यों यह प्रत्यक्ष रूपांतरण निर्माता के अलावा प्रति निर्माता कॉल करने के लिए प्रयास कर रहा है?

यह त्रुटि संदेश एक अस्थायी B बनाई गई है जो तब कॉपी-निर्माण के लिए प्रयोग किया जाता है, लेकिन क्यों से स्पष्ट है? मानक में यह कहां है?

+0

है आपका प्रश्न, किसी भी मौके से, [यह एक] से संबंधित है (http://stackoverflow.com/questions/11221242/is-this-a-copy-constructor)? :) –

+0

@EitanT आप कैसे जानते थे? –

+0

क्योंकि मैंने कुछ मिनट पहले उस प्रश्न की समीक्षा की है :) –

उत्तर

13
B b2 = a; 

इस रूप में Copy Initialization जाना जाता है।

  1. B (const A& a) का उपयोग करके a से प्रकार B की एक वस्तु बनाएँ:

    यह THH निम्नलिखित है।

  2. B (const B& b) का उपयोग कर बनाई गई अस्थायी वस्तु को b2 पर कॉपी करें।
  3. ~B() का उपयोग कर अस्थायी वस्तु को नष्ट करें।

त्रुटि आप प्राप्त चरण 1 पर नहीं है बल्कि कदम पर 2.

Where is this in the standard?

सी ++ 03 8.5 initializers
पैरा 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

लेकिन सीधे रूपांतरण कन्स्ट्रक्टर का उपयोग क्यों नहीं करते? –

+0

@LuchianGrigore: यह करता है। प्रतिलिपि * निर्माण के दौरान * रूपांतरण के दौरान किया गया है। कन्स्ट्रक्टर की प्रतिलिपि बनाने के लिए कॉल भी elided किया जा सकता है, लेकिन यह संकलक पर निर्भर करता है। इसके अलावा, अभी भी प्रतिलिपि बनाने की जरूरत है सुलभ। –

+0

हां, मुझे यह मिला (और मुझे पता है कि उन्हें बिना किसी कॉल के कहा जाता है या नहीं) पर ध्यान दिया जाना चाहिए। लेकिन यह सिर्फ एक कदम में क्यों नहीं करता है? अस्थायी 'बी' की आवश्यकता क्यों है? –

संबंधित मुद्दे