为什么在任务后打电话给攻击函数
Why is the destructor called after assignment?
为什么在线路mystring = "Hello, there!";
之后在这里打电话给destructor这还不是它远离范围。我绝对错过了C 的一些怪癖!
我知道该行调用默认复制构造函数,在复制构造函数返回后总是调用destructor?
作为旁注,我正在使用C 03,否C 11。
编辑:另外,请注意,我知道以下程序导致的双重删除。我在这里实验。只是想引起您的注意。
class MyString
{
private:
char* mystring;
int m_length;
public:
MyString(const char* str="")
{
assert(str);
m_length = strlen(str) + 1;
mystring = new char[m_length];
for (int i = 0; i < m_length; ++i)
mystring[i] = str[i];
mystring[m_length-1] = ' ';
}
~MyString()
{
delete[] mystring;
}
};
int main()
{
MyString mystring("");
mystring = "Hello, there!";
cout << "Destructor not yet called ";
}
,因为您没有类的分配操作员,该操作员将字符串字面的 mystring = "Hello, there!";
转变为3份操作。
-
首先,它必须从字符串文字中构造一个临时对象。
-
然后,它将该临时性使用并与默认副本(PRE C 11(/MOVE(post C 11(如果未另行删除((分配操作员为类生成的编译器。
-
然后必须销毁其创建的临时对象。这就是为什么您会在该表达式结束时看到对破坏者的呼叫。
请注意,由于临时对象在
之后被破坏mystring = "Hello, there!";
现在删除了指针mystring
所持的,您无法再访问它。当它被销毁时,它也会导致双重删除,这是不确定的行为并会导致并发症。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- C++Brute Force攻击函数不会返回结果
- 您可以在不调用构造函数的情况下调用攻击器吗?
- 为什么在任务后打电话给攻击函数
- 如果(玩家[P] .setCoin(Gameboard,Input))将其命名为“在线”游戏板的攻击函数)
- 保存对象的攻击函数并稍后称呼它是明确定义的行为
- 我如何明确称为STD迭代剂的攻击函数
- 我可以称呼班级显性的构造函数和攻击函数
- 称呼该指针和攻击函数
- 如果一个易受攻击的函数的输入是安全的,那么它有可能利用它吗