c++ - 为什么显示 - -"cannot pass objects of non-trivially-copyable type"?

标签 c++ linux os.execl

您不必从头开始查看完整的代码。问题出在 main 中的 execl(..) 语句中。代码是——

#include <cstdio>
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <vector>

#define li long int

using namespace std;


char TypedCommandInTerminal[1001];
vector <string> ValidCommands,TypedCommand;


void ShowTerminal()
{
    cout<<"User:$ ";
    gets(TypedCommandInTerminal);
}


void PushCommands()
{
    ValidCommands.push_back("mkdir");
}


void GetCommandIntoVector()
{
    TypedCommand.clear();

    char *p = strtok(TypedCommandInTerminal," ");

    while(p)
    {
        TypedCommand.push_back(p);
        p = strtok(NULL," ");
    }
}

bool MatchCommand(string Command)
{
    li i;

    for(i=0;i<ValidCommands.size();i++)
    {
        if(ValidCommands[i].compare(Command)==0)
        {
            return true;
        }
    }
    return false;
}



int main()
{
    int status;
    string StoredCommand;

    PushCommands();
    while(true)
    {
        ShowTerminal();
        if(fork()!=0)
        {
            waitpid(-1,&status,0);
        }
        else
        {
            GetCommandIntoVector();
            if(MatchCommand(TypedCommand[0]))
            {
                StoredCommand = "mkdir";
                if(StoredCommand.compare(TypedCommand[0])==0)
                {
                    execl("/bin/mkdir","mkdir",TypedCommand[1],NULL);/*ERROR*/
                }
            }
            else
            {
                cout<<"Command Not Available\n";
                return -1;
            }
        }
    }
    return 0;
}

我正在尝试在 Linux 中使用 C++ 设计一个简单的终端。我在这里要做的是——将控制台中的这个命令作为输入——“mkdir ab”。然后我设法标记这个字符串,并在 TypedCommand[0] 中保留“mkdir”,在 TypedCommand[1] 中保留“ab”。问题是当我在 execl 编译器中编写“TypedCommand[1]”时出现错误——“无法传递非平凡可复制类型的对象……” 我删除了 TypedCommand[1] 并手动编写了“ab”来代替它。代码运行并在执行目录中创建了一个名为“ab”的文件夹。所以看起来 execl 工作正常。

我需要以某种方式在 execl 中传递保存在 TypedCommand[1] 中的第二个字符串...这里有什么问题吗?

最佳答案

您将 std::string 对象作为可选参数传递给函数(execl 接受可变数量的参数)。 std::string 具有非平凡的构造函数、析构函数等,不能以这种方式使用。在这种情况下,无论如何你都想传递一个指向字符串的指针,所以改变

execl("/bin/mkdir","mkdir",TypedCommand[1],NULL);

execl("/bin/mkdir","mkdir",TypedCommand[1].c_str(),NULL);

关于c++ - 为什么显示 - -"cannot pass objects of non-trivially-copyable type"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472119/

相关文章:

c++ - 既然可以使用函数引用,为什么还要使用仿函数

c++ - 在 Qt4 中创建可调整大小的侧边栏

python - python 中 os.execl() 和 os.execv() 的区别

c++ - execlp 多个 "programs"

c - GList(glib-doubly-linked-list)线程安全吗?

c - open() 第一次尝试失败

c++ - 如何在 Windows 下用 C++ 在远程机器上启动一个进程

java - 如何在 Java 中使用 & 运算符?移植C代码

linux - WSL2 Docker Linux 卷权限问题

linux - 在 shell 脚本中创建结构(数据结构)