我确信这在某个地方得到了解答,但我缺乏制定搜索的词汇.
#include <iostream>
class Thing
{
public:
int value;
Thing();
virtual ~Thing() { std::cout << "Destroyed a thing with value " << value << std::endl; }
};
Thing::Thing(int newval)
{
value = newval;
}
int main()
{
Thing *myThing1 = new Thing(5);
std::cout << "Value 1: " << myThing1->value << std::endl;
Thing myThing2 = Thing(6);
std::cout << "Value 2: " << myThing2.value << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出表明myThing2被破坏了,我的myThing1没有.
所以...我需要以某种方式手动解构它吗?这是内存泄漏吗?我应该避免在这种情况下使用*,如果是这样,何时适合?
当参数作为 char** 传入时,从字符串向量到 char* 向量再到 char** 是有效的,但转换似乎有问题,我无法找到差异。
有一个更好的方法吗?
vector<string> args;
/* code that correctly parses args from user input */
pid_t kidpid = fork();
if (kidpid < 0)
{
perror("Internal error: cannot fork.");
return -1;
}
else if (kidpid == 0)
{
// I am the child.
vector<char*>argcs;
for(int i=1;i<args.size();i++)
{
char * temp = new char[args.at(i).length()];
for(int k=0;k<args.at(i).length();k++)
{
temp[k] = args.at(i).at(k);
}
argcs.push_back(temp);
}
char** argv = new char*[argcs.size() + 1];
for (int i = 0; i < …Run Code Online (Sandbox Code Playgroud)