[英]MSVC direct constructor call extension
In this response , tloveless pointed out that it's possible in MSVC to use this->foo::foo(42);
在此回应中 , tloveless指出MSVC中可能使用
this->foo::foo(42);
;。
for constructor delegation
to directly call a constructor:
让构造函数委托
直接调用构造函数:
#include <iostream>
struct foo
{
int m;
foo(int p) : m(p) { std::cout << "foo("<<p<<")\n"; }
foo()
: m(0)
{
this->foo::foo(42);
std::cout << "foo(), " << m << "\n";
}
};
int main()
{
foo f;
std::cin.ignore();
}
I was surprised that this even compiles in MSVC; 令我惊讶的是,它甚至可以在MSVC中编译。 clang++, g++ and me agree it's illegal, eg [class.ctor]/2 "Because constructors do not have names, they are never found during name lookup"
clang ++,g ++和我都认为这是非法的,例如[class.ctor] / 2“由于构造函数没有名称,因此在名称查找过程中永远找不到它们”
However, MSVC doesn't even emit a warning with /Wall
and without language extensions /Za
in MSVC12 Update 1 (2013) and MSVC10 SP1 (2010). 但是,在MSVC12 Update 1(2013)和MSVC10 SP1(2010)中,带有
/Wall
并且没有语言扩展名/Za
MSVC甚至不会发出警告。
The output is: 输出为:
foo(42) foo(), 42
in both versions. 在两个版本中。 So there's no temporary created, but a constructor called.
因此,没有临时创建,而是调用了一个构造函数。
Questions: 问题:
/Za
and the list of extensions don't seem to think so) /Za
和扩展名列表似乎并不这样认为) (I tagged this question with the [delegating-constructors] tag since it reminds me heavily of this feature) (我用[delegating-constructors]标签标记了这个问题,因为它使我很想起此功能)
meta-info: I'm almost sure this question is a duplicate, since this feature is somewhat known. meta-info:我几乎可以肯定这个问题是重复的,因为这个功能有些人知道。 For example, see this answer to a "similar question".
例如,请参见“类似问题”的答案 。 Please do not hesitate closing this as a dup if you can find an answer that describes this feature.
如果您可以找到描述此功能的答案,请不要犹豫将其作为重复项关闭。
It is not constructor delegating. 这不是构造函数的委托。 Try following code:
尝试以下代码:
#include <iostream>
class C{
public:
C() { std::cout << "C" << std::endl; }
~C() { std::cout << "~C" << std::endl; }
};
struct foo
{
int m;
C c;
foo(int p) : m(p) { std::cout << "foo("<<p<<")\n"; }
foo()
: m(0)
{
this->foo::foo(42);
std::cout << "foo(), " << m << "\n";
}
};
int main()
{
foo f;
}
According to output field "c" is initialized twice but destroyed only once. 根据输出字段,“ c”被初始化两次,但仅被破坏一次。 As zneak noted, It is similar to
new (this) foo(42)
. 正如zneak所指出的,它类似于
new (this) foo(42)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.