2017-09-03 16 views
0

the official tutorialの例に基づいて問題を再現しました。ブーストプログラムオプション - 関数の結果からarg名を渡す

#include <string> 
#include <boost/program_options.hpp> 
#include <iostream> 

namespace po = boost::program_options; 
using namespace std; 

const char* withAlias(const char* name, const char* alias) 
{ 
    return (string(name) + "," + alias).c_str(); 
} 

int main(int argc, char** argv) 
{ 
    po::options_description desc; 
    const auto name = withAlias("compression", "c"); 
    desc.add_options() 
     (name, po::value<int>(), "compression bla bla"); // this doesn't work 
     ("compression,c", po::value<int>(), "asdasdasd"); // this works 

    po::variables_map vm; 
    po::store(po::parse_command_line(argc, argv, desc), vm); 
    po::notify(vm); 

    if (vm.count("compression")) 
     cout << "Compression set to " << vm["compression"].as<int>() << endl; 
    else 
     cout << "Compression not set" << endl; 
    return 0; 
} 

私は私のプログラムを実行 : unrecognized option '--compression'を:my_bin --compression 5が、それは述べ、エラーがスローされます。

エイリアス(別名("compression", ...))を使用しない場合、これは期待どおりに動作します。

名前文字列に,があり、文字列リテラルとして渡されない場合にのみ発生します。

原因を突き止めることはできません。

+0

あなたは "-c - 圧縮" 'てみましたか'? (今すぐリンクを読んで、おそらく動作しません) –

+0

@ YuvalBen-Arieちょうど、動作しなかった、同じエラー –

答えて

2
const char* withAlias(const char* name, const char* alias) 
{ 
    return (string(name) + "," + alias).c_str(); 
} 

std::stringオブジェクトが破棄されると、文字列ポインタが無効になります。あなたがそうのように、周りのstd::stringを維持する必要が

std::string withAlias(std::string name, std::string name) 
{ 
    return name + "," + alias; 
} 

int main(int argc, char** argv) 
{ 
    po::options_description desc; 
    auto name = withAlias("compression", "c"); 

    desc.add_options() 
     (name.c_str(), po::value<int>(), "compression bla bla"); 
    ... 
+0

'const char *'はコピーされていませんか? –

+0

署名を 'std :: string withAlias'に変更しようとしましたが、' .c_str() 'が呼び出されてもそれでも失敗します。 –

+0

@GioraGuttsait、はい、それは単なるポインタです。基礎となるデータは別の問題です。 – Frank

関連する問題