[英]Why shows --“cannot pass objects of non-trivially-copyable type”?
您不必从头开始完成完整的代码。 问题出在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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.