简体   繁体   English

这些构造函数有什么区别?

[英]What's the difference between these constructors?

I'd like to know what is the difference between these two constructors: 我想知道这两个构造函数之间的区别:

List<type*> list = List<type*>();

and

List<type*> list;

The container List was written by me and has a user-defined constructor which takes no parameters. 容器List是由我编写的,并且具有一个不带参数的用户定义的构造函数。

In my opinion the first line is correct and the second one looks like Java. 我认为第一行是正确的,第二行看起来像Java。 However, both compile. 但是,两者都可以编译。 So, what is the difference between these two statements? 那么,这两个语句之间有什么区别?

The first one requires an accessible copy or move constructor while the second one does not. 第一个需要可访问的副本或移动构造函数,而第二个则不需要。

Consider for example this demontsrative program. 例如考虑这个解梦程序。 If you will not use MS VC++ then the program shall not compile.:) 如果您不使用MS VC ++,则该程序将无法编译。

#include <iostream>

class A
{
public:    
    A() {}
private:    
    A( const A& ) { std::cout << "A( const A & )" << std::endl; }
};              

int main()
{
    A a = A();
}

because the copy constructor is inaccessible even if otherwise the copy operation could be elided. 因为即使无法执行复制操作,也无法访问复制构造函数。

Also using the first one provides that the corresponding object will be value-initialized while using the second one provides that the corresponding object will be default initialized. 同样使用第一个提供相应的对象将被值初始化,而使用第二个提供相应的对象将被默认初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM