Are temporary objects in C++ const indeed?

前端 未结 6 1742
走了就别回头了
走了就别回头了 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:40

    It all depends on the return type of the function.

    //Temporary objects: nameless objects that are only usable in current statement
    Object function();           //Return a temporary object by value (using copy constructor)
    const Object function();     //Return a const temp object by value
    
    //references, return a reference to an object existing somewhere else in memory
    Object & function();         //Return an object reference, non-const behaves as any other non-const
    const Object & functon();    //Return const obj reference, behaves as any other const
    

提交回复
热议问题