在代码中创建 argc argv [英] create argc argv in the code

查看:26
本文介绍了在代码中创建 argc argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新手问题,但我就是想不通:

Hi very newbie question but I just can't figure it out:

我有一个名为 bar 的函数

I have a function named bar

class foo
{
    public:
        bool bar(int argc, char** argv);
}

argv 应该包含

"--dir" and "/some_path/"

如何创建 argv 和 argc 以便将它们传递给 bar() ?我尝试了很多方法,但我无法正确地获得指针和类型转换.

How do I create argv and argc so that I can pass them into bar() ? I've tried many ways but I just can't get pointer and type conversion right.

因此,我想在代码中创建它,而不是从命令行获取 argv.

So instead of getting argv from command line, I want to create it in the code.

感谢您的任何意见!

推荐答案

我最喜欢的方式是这样的:

My favourite way is like this:

std::vector<std::string> arguments = {"--dir", "/some_path"};

std::vector<char*> argv;
for (const auto& arg : arguments)
    argv.push_back((char*)arg.data());
argv.push_back(nullptr);

f.bar(argv.size() - 1, argv.data());

注意,如果参数是静态的并且不会改变,那么这有点矫枉过正.但是这种方法具有符合 RAII 的优点.它为您管理内存并在适当的时候删除对象.所以如果参数列表是动态的,那么它是最干净的方式.

Note, that if arguments are static and do not change, then this is a little bit overkill. But this approach has advantage of being RAII compliant. It manages memory for you and deletes objects at right moment. So if argument list is dynamic, then it is the cleanest way.

除此之外,如果 f.bar 修改 argv 数组中的数据,则此代码在技术上是 UB.通常情况并非如此.

Beside that, this code technically is UB if f.bar modifies data in argv array. Usually this is not the case.

这篇关于在代码中创建 argc argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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