与此相关
我想知道嵌套名称说明符究竟是什么?我在草稿中查了一下但是我能理解语法,因为我还没有学过任何编译器设计课程.
void S(){}
struct S{
S(){cout << 1;}
void f(){}
static const int x = 0;
};
int main(){
struct S *p = new struct ::S;
p->::S::f();
S::x;
::S(); // Is ::S a nested name specifier?
delete p;
}
Run Code Online (Sandbox Code Playgroud) 在我学习C++的过程中,我偶然发现了编写复制构造函数和赋值运算符的文章,该文章提出了一种机制来避免复制构造函数和赋值运算符之间的代码重复.
为了总结/复制该链接的内容,建议的机制是:
struct UtilityClass
{
...
UtilityClass(UtilityClass const &rhs)
: data_(new int(*rhs_.data_))
{
// nothing left to do here
}
UtilityClass &operator=(UtilityClass const &rhs)
{
//
// Leaves all the work to the copy constructor.
//
if(this != &rhs)
{
// deconstruct myself
this->UtilityClass::~UtilityClass();
// reconstruct myself by copying from the right hand side.
new(this) UtilityClass(rhs);
}
return *this;
}
...
};
Run Code Online (Sandbox Code Playgroud)
这似乎是避免代码重复同时确保"编程完整性"的好方法,但需要权衡浪费工作的风险 - 然后分配嵌套内存,而不是重新使用(正如其作者指出的那样).
但我不熟悉其核心语法:
this->UtilityClass::~UtilityClass()
Run Code Online (Sandbox Code Playgroud)
我假设这是一种调用对象的析构函数(破坏对象结构的内容)同时保持结构本身的方法.对于C++新手来说,语法看起来像是对象方法和类方法的奇怪混合.
有人可以向我解释这个语法,还是指向一个可以解释它的资源?
该呼叫与以下内容有何不同?
this->~UtilityClass()
Run Code Online (Sandbox Code Playgroud)
这是合法的电话吗?这是否会破坏对象结构(没有堆;从堆栈中弹出)?