2012-06-03 5 views
3

나는 올바르게 이해하고 싶습니다. 의 C++ 표준 : : 문자열의 세 가지 경우 아래의 기능이 생성됩니다 :std :: string의 유효 기간이 인수로 전달되었습니다.

  • 한 호출자의 (S1)에 대한() 나는 호출자의 S2 매개 변수에 대한 할당 생성자
  • 하나를이라고 믿는 것을 통해()를 통해 기능이 복사 생성자를 통해 S3에 대한 복사 생성자
  • 하나

내가 수정 있습니까? 그렇다면 3 가지 경우 모두 범위를 벗어나면 정리됩니다. 나는 정말로 이것이 좋은 코드인지 아닌지를 묻지 않고있다. 이해가 정확하다. 그들이이 될 것으로 보인다

void caller(void) { 
    std::string s1 = "hi"; 
    callee(s1); 
} 

void callee(std::string s2) { 
    std::string s3 = s2; 
} 
+1

내가 아는 한 "할당 생성자"와 같은 것은 없습니다. 한 유형에서 다른 유형으로 변환하는 "변환 생성자"가 있습니다. –

답변

2

거의 정확합니다.

s1의 생성 여부에 따라 3 개 또는 4 개의 문자열이 생성 될 수 있으며, 각 경우 생성자가 생성되어 생성됩니다. 외관에도 불구하고, 어떤 할당 연산자에 대한 호출이 없습니다.

void caller(void) { 
    //A temporary std::string is constructed with the 
    //basic_string(const CharT* s, const Allocator& alloc = Allocator()) 
    //constructor. 
    //(In the call, `s` is initialized to point to the first element of "hi".) 
    //This temporary is then move constructed in to s1. 
    //The move constructor is 
    //basic_string(basic_string&& other) 
    //This move construction may be elided. 
    std::string s1 = "hi"; //At the end of the full expression (ie, at the semicolon) 
          //the lifetime of the temporary string ends (unless 
          //the construction of s1 is elided, in which 
          //case the temporary becomes s1, and its lifetime ends 
          //with s1). 
    //s2 is copy constructed from s1 
    //The copy constructor is 
    //basic_string(const basic_string& other) 
    callee(s1); 
    //the lifetime of s1 ends 
} 

void callee(std::string s2) { 
    //s3 is copy constructed from s2 
    std::string s3 = s2; 
    //the lifetime of s3 ends 
    //the lifetime of s2 ends 
} 
3

복사본 사방 만들어 가정하지 마십시오. 실제로, 복사 - 추출은 생각보다 더 자주 발생합니다. 컴파일러는 복사가 부작용이있는 경우에도, 여분의 복사본을 최적화 할 무료입니다 : 문자열이 방법은 인라인이며, 컴파일러가 어떤 부작용이 발생하지 감지 한 경우, 또한

void caller(void) { 
    std::string s1 = "hi"; 
    //theoretically, s1 is copied here 
    //in practice, the compiler will optimize the call away 
    functionCallee(s1); 
} 

void callee(std::string s2) { 
    //although s2 is passed by value, it's probably no copy was created 
    //most likely, it's exactly the same as s1 from the calling context 
    std::string s3 = s2; 
} 

수도조차 만들 수 있습니다.

+0

감사합니다. 그래서 내가 설명한대로 메모리 누수가 없습니까? –

+3

이러한 상황에서 copy-elision이 어떻게 적용되는지 나는 알지 못합니다 ... – Mankarse

+4

@JohnFitzpatrick'new' 또는'malloc'을 사용하지 않으면 결코 메모리 누출이 없습니다. –

관련 문제