在C ++中使用c样初始化或压缩器初始化是否更好? [英] Is it considered better to use c-like initialization or contructor initialization in C++?

查看:158
本文介绍了在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); 直接初始化。即使对于一般的类类型,编译器几乎可以生成相同的代码,但是复制初始化要求类不具有被声明为显式的复制构造函数

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

elision被明确允许和鼓励,但是as if构造必须仍然是有效的,即复制构造函数必须是可访问的并且不是显式的或删除的。例如:

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天全站免登陆