Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

029 「初期化文つき条件文」のコード例 #110

Open
akinomyoga opened this issue Oct 15, 2017 · 1 comment
Open

029 「初期化文つき条件文」のコード例 #110

akinomyoga opened this issue Oct 15, 2017 · 1 comment

Comments

@akinomyoga
Copy link
Contributor

使い所として以下の例が提示されていますが、

if ( auto ptr = std::make_unique<int>(42) ; ptr )
{
    // 処理
}

これは以下の点が気になります。

  1. 従来の C++ でも以下のようにすればできるということ、
if ( auto ptr = std::make_unique<int>(42) )
{
    // 処理
}
  1. std::make_unique<int>(42) は例外を投げるか、bool にキャストして true になるかのどちらかしかない気がします。だとすると、条件分岐の意義がないように思われること。

この新しい構文は、宣言される変数と実際に条件分岐に使われる式が異なる場合に力を発揮するので、例えば以下のような感じの例にするのはいかがでしょう。

if ( auto ptr = do_something(); *ptr )
{
    // 処理
}
@yumetodo
Copy link
Contributor

https://qiita.com/yumetodo/items/245e94a0e85db9bf5cbb#comment-804fa063c70a338358cb
で私が前にかいた

if(std::size_t pos = s.find_first_of(' '); std::string::npos != pos){
   //なんか
}

みたいな例のほうがより実用的では

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants