在构造函数中使用临时作为默认参数 [英] Use a temporary as default argument in constructor

查看:65
本文介绍了在构造函数中使用临时作为默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我们可以将对象分配给非const引用。这样就可以了:

In C++, we can assign an object to a non-const reference. So this works:

Foo &foo = Foo();

但是,C ++不允许将临时变量分配给非const引用。所以这是不允许的:

But, C++ doesn't allow a temporary to be assigned to a non-const reference. So this is not allowed:

Bar::Bar(Foo &foo = Foo()) {}

但这是允许的

Bar::Bar(const Foo &foo = Foo()) {}

I这里有三个问题:


  1. 在最后一种情况下foo的作用域是什么?即使退出构造函数后,它仍然存在吗?根据我的阅读,如果将临时对象分配给const引用,则会修改其生存期,在这种情况下,它将占用为其分配的引用的生存期。默认参数(在这种情况下为foo)的有效期限是多少?

  2. 我在MSVC中尝试了第二个示例,但它没有抱怨。我还注意到,临时文件的寿命仍在延长。因此,我可以在构造函数退出后使用foo。

  3. 我的情况要求以这种方式向构造函数提供默认参数,而我将需要在构造函数中修改该参数(因此无法将其设为const)。而且我还需要在构造函数退出后使用foo。满足这种情况的最佳设计是什么?

预先感谢。

推荐答案


在最后一种情况下 foo 的范围是什么?

foo 是一个构造函数(同样适用于常规函数),因此当< a href = https://stackoverflow.com/a/12554621/241631>包含对构造函数的调用的完整表达式结束。 感谢 aschepler

foo is a constructor (same applies to regular functions too) argument, so its lifetime ends when the full expression containing the call to the constructor ends. Thanks aschepler!


默认参数的寿命是多少,在这种情况下为foo?

What is the lifetime of the default argument, in this case foo?

您延长了默认参数的寿命通过将其绑定到 Foo const& foo ,因此其生存期将与其绑定的引用相匹配,即直到构造函数主体退出。

You extended the lifetime of the default argument by binding it to Foo const& foo, so its lifetime will match that of the reference it's bound to, i.e. until the constructor body exits.


我在MSVC中尝试了第二个示例,但它没有抱怨。

I tried the second example in MSVC and it didn't complain.

如果将警告级别设置为 / W4 ;在这种情况下,它会警告您使用的是非标准扩展名。 AFAIK,其语义与前面的情况相同。

It does if you set the warning level to /W4; in that case it'll warn you about a non-standard extension being used. AFAIK, the semantics are the same as the previous case.


我的场景要求以这种方式向构造函数提供默认参数,我需要修改构造函数中的参数(因此我无法将其设为const)。而且我还需要在构造函数退出后使用foo。

My scenario demands the default argument to constructor in this manner and I will need to modify the argument in the constructor (so I cannot make it const). And I also need to use foo after the constructor has exited.

这取决于您是否要将其保存为<$的成员。 c $ c> Bar 与否。如果是前者,则使用右值引用并移动参数

It depends on whether you want to save it as member of Bar or not. If it's the former, use an rvalue reference and move the argument

Bar::Bar(Foo&& foo = Foo()) : f_(std::move(foo)) {} // f_ is a member of type Foo



的成员

否则,只需忽略默认参数即可。您还可以创建两个重载来覆盖不同的情况。

Otherwise, just leave out the default argument. You can also create both overloads to cover different situations.

这篇关于在构造函数中使用临时作为默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆