开发者

Is it safe to access a default argument by reference?

开发者 https://www.devze.com 2023-03-02 04:22 出处:网络
I have a function that looks like this: class SomeClass { // ... }; vo开发者_如何学编程id some_function(const SomeClass& arg = SomeClass());

I have a function that looks like this:

class SomeClass {
    // ...
};

vo开发者_如何学编程id some_function(const SomeClass& arg = SomeClass());

The function some_function accesses its argument by reference and has a default value. Is it safe to do this, or will the reference be invalid when I call the function without an argument?


Yes, it's safe. A const reference bound to a temporary extends the life of that temporary to the lifetime of the reference. The same is true of rvalue references.


It will be valid. The lifetime of the temporary used as a default value is a superset of the lifetime of the function call. This is also no different than if you had passed in a temporary explicitly (default arguments are basically syntactic sugar, saving you from typing, but behave more or less identically to arguments passed explicitly.

0

精彩评论

暂无评论...
验证码 换一张
取 消