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

前端 未结 3 1706
难免孤独
难免孤独 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

    It depends on what you mean by "what move does". To satisfy your curiosity, I think what you're looking to be told about the existence of Uniqueness Type Systems and Linear Type Systems.

    These are types systems that enforce, at compile-time (in the type system), that a value only be referenced by one location, or that no new references be made. std::unique_ptr is the best approximation C++ can provide, given its rather weak type system.

    Let's say we had a new storage-class specifier called uniqueref. This is like const, and specifies that the value has a single unique reference; nobody else has the value. It would enable this:

    int main()
    {
        int* uniqueref x(new int); // only x has this reference
    
        // unique type feature: error, would no longer be unique
        auto y = x; 
    
        // linear type feature: okay, x not longer usable, z is now the unique owner
        auto z = uniquemove(x);
    
        // linear type feature: error: x is no longer usable
        *x = 5;
    }
    

    (Also interesting to note the immense optimizations that can be taking, knowing a pointer value is really truly only referenced through that pointer. It's a bit like C99's restrict in that aspect.)

    In terms of what you're asking, since we can now say that a type is uniquely referenced, we can guarantee that it's safe to move. That said, move operates are ultimately user-defined, and can do all sorts of weird stuff if desired, so implicitly doing this is a bad idea in current C++ anyway.

    Everything above is obviously not formally thought-out and specified, but should give you an idea of what such a type system might look like. More generally, you probably want an Effect Type System.

    But yes, these ideas do exist and are formally researched. C++ is just too established to add them.

提交回复
热议问题