在C ++中使用类似c的初始化或构造函数初始化是否更好? [英] Is it considered better to use c-like initialization or constructor initialization in C++?

查看:101
本文介绍了在C ++中使用类似c的初始化或构造函数初始化是否更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

何时应使用直接初始化以及何时进行复制初始化?

我都知道

int a = 1;

int a(1);

在C ++中工作,但是哪个更好用?

work in C++, but which one is considered better to use?

推荐答案

对于 int 没有什么区别。 int a = 1; 语法为 copy-initialziation ,而 int a(1); 直接初始化。几乎可以保证即使对于普通的类类型,编译器也可以生成相同的代码,但是复制初始化要求类 not 具有一个声明为 explicit

For int there's no difference. The int a = 1; syntax is copy-initialziation, while int a(1); is direct-initialization. The compiler is almost guaranteed to generate the same code even for general class types, but copy-initialization requires that the class not have a copy constructor that is declared explicit.

要说明这一点,直接初始化直接调用相应的构造函数:

To spell this out, direct-initialization directly calls the corresponding constructor:

T x(arg);

另一方面,复制初始化行为好像复制了一个副本:

On the other hand, copy-initialization behaves "as if" a copy is made:

T x = arg; // "as if" T x(T(arg));, but implicitly so

明确允许并鼓励使用省略号,但是好像构造必须仍然有效,即,复制构造函数必须是可访问的,并且不是明确的或删除的。示例:

Copy-elision is explicitly allowed and encouraged, but the "as if" construction must still be valid, i.e. the copy constructor must be accesible and not explicit or deleted. An example:

struct T
{
    T(int) { } // one-argument constructor needed for `T x = 1;` syntax

    // T(T const &) = delete;            // Error: deleted copy constructor
    // explicit T(T const &) = default;  // Error: explicit copy constructor
    // private: T(T const &) = default;  // Error: inaccessible copy constructor
};

这篇关于在C ++中使用类似c的初始化或构造函数初始化是否更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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