What are the differences in string initialization in C++?

前端 未结 4 1640
面向向阳花
面向向阳花 2021-02-04 01:53

Is there any difference between

std::string s1(\"foo\");

and

std::string s2 = \"foo\";

?

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 02:39

    Yes and No.

    The first is initialized explicitly, and the second is copy initialized. The standards permits to replace the second with the first. In practice, the produced code is the same.

    Here is what happens in a nutshell:

    std::string s1("foo");
    

    The string constructor of the form:

    string ( const char * s );
    

    is called for s1.

    In the second case. A temporary is created, and the mentioned earler constructor is called for that temporary. Then, the copy constructor is invoked. e.g:

    string s1 = string("foo");
    

    In practice, the second form is optimized, to be of the form of the first. I haven't seen a compiler that doesn't optimize the second case.

提交回复
热议问题