Could a smart compiler do all the things std::move does without it being part of the language?

前端 未结 3 1705
难免孤独
难免孤独 2021-01-06 15:21

This is a bit theoretical question, but although I have some basic understanding of the std::move Im still not certain if it provides some additional functionality to the la

3条回答
  •  不思量自难忘°
    2021-01-06 15:45

    Doing this the way you suggest is a lot more complicated than necessary:

    std::string s1="STL";
    std::string s2(s1);
    std::cout << s1 <

    In this case, it is fairly sure that a copy is meant. But if you drop the last line, s1 essentially ends its lifetime after the construction of s2.

    In a reference counted implementation, the copy constructor for std::string will only increment the reference counter, while the destructor will decrement and delete if it becomes zero.

    So the sequence is

    1. (inlined std::string::string(char const *))
      1. determine string length
      2. allocate memory
      3. copy string
      4. initialize reference counter to 1
      5. initialize pointer in string object
    2. (inlined std::string::string(std::string const &))
      1. increment reference counter
      2. copy pointer to string representation

    Now the compiler can flatten that, simply initialize the reference counter to 2 and store the pointer twice. Common Subexpression Elimination then finds out that s1 and s2 keep the same pointer value, and merges them into one.

    In short, the only difference in generated code should be that the reference counter is initialized to 2.

提交回复
热议问题