这是什么语法 - new(this)T(); [英] what is this syntax - new (this) T();

查看:181
本文介绍了这是什么语法 - new(this)T();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的C ++代码:

  T :: operator =(const T& t)
{
...
new(this)T
...
}

这行对我来说很陌生: code> new(this)T(t);



我可以看到它是调用复制构造函数填充this ,但不知何故我只是不能理解的语法。猜猜我这么习惯 this = new T(t);



你能帮我吗? p>

解决方案

这就是所谓的新的布局运算符。它在括号中的表达式指定的地址处构造对象。例如,可以用以下方式定义复制赋值运算符。

  const C& C :: operator =(const C& other){
if(this!=& other){
this->〜C //生存期*这结束
new(this)C(other); // C类创建的新对象
}
return * this;
}

在本例中,首先使用显式调用析构函数,然后在这个地址使用复制构造函数创建一个新对象。



这是新的操作符不分配新的内存区。它使用已分配的内存。



此示例取自C ++标准。至于我,我不会返回一个const对象。将操作符声明为

更正确。 $ b

  C& C :: operator =(const C& other); 


I run into such C++ code:

T& T::operator=(const T&t) 
{
   ...
   new (this) T(t);
   ...
}

This line looks so foreign to me:new (this) T(t);

I can see it is calling the copy constructor to populate "this", but somehow I just cannot make sense out of the syntax. Guess I am so used to this = new T(t);

Could you help me out?

解决方案

It is so-called the new placement operator. it constructs an object at address specified by the expression in parentheses. For example the copy assignment operator can be defined the following way

const C& C::operator=( const C& other) {
   if ( this != &other ) {
      this->~C(); // lifetime of *this ends
      new (this) C(other); // new object of type C created
   }
   return *this;
}

In this example at first the current object is destroyed using an explicit call of the destructor and then at this address a new object is created using the copy constructor.

That is this new operator does not allocate a new extent of memory. It uses the memory that was already allocated.

This example is taken from the C++ Standard. As for me I would not return a const object. It would be more correctly to declare the operator as

C& C::operator=( const C& other);

这篇关于这是什么语法 - new(this)T();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆