Are temporary objects in C++ const indeed?

前端 未结 6 1764
走了就别回头了
走了就别回头了 2021-01-06 10:11

I always believed that temporary objects in C++ are automatically considered as const by the compiler. But recently I experienced that the following example of code:

6条回答
  •  渐次进展
    2021-01-06 10:50

    Answering the question first, they are not actually const. You may not bind one to a non-const reference. This was probably done to prevent errors in certain situations where they would be passed as a parameter to a function that modifies them, only for the changes to be made to a temporary object and not the intended target.

    Allowing non-const operations on a temporary is especially useful when you wish to call "swap" on it with a local variable.

    std::vector local;
    method_that_returns_a_vector().swap( local );
    

    Before the days of move semantics, this was considered the most efficient way to return a large data set and acquire it without copying all the data.

提交回复
热议问题