在堆栈上声明一个对象的两种方式之间的区别 [英] Difference between two ways of declaring an object on the stack

查看:179
本文介绍了在堆栈上声明一个对象的两种方式之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个声明之间有什么区别,假设我没有在类 Beatle operator = c>

What's the difference between the following two declarations, assuming I have not specified a copy constructor and operator= in class Beatle?

Beatle john(paul);

Beatle john = paul;

编辑:

在对象赋值中,除非另有说明,否则操作符 = 隐式调用复制构造函数? >

In objects assignment, the operator = implicitly calls the copy constructor unless told otherwise?

推荐答案

它们是不同的语法结构。第一个是直接初始化,第二个是复制初始化。它们的行为几乎相同,只是第二个需要一个非< - code>显式的构造函数。

They're different grammatical constructions. The first one is direct initialization, the second is copy initialization. They behave virtually identically, only that the second requires a non-explicit constructor.*

const int i = 4; code>很好,但 const int i; i = 4; 不是。

To wit: const int i = 4; is fine, but const int i; i = 4; is not.

*)更准确地说:如果相关构造函数声明为 explicit 。因此,直接初始化提供了一个自由转换:

*) More accurately: The second version does not work if the relevant constructor is declared explicit. More generally, thus, direct-initialization affords you one "free" conversion:

struct Foo { Foo(std::string) {} };

Foo x("abc");  // OK: char(&)[4] -> const char * -> std::string -> Foo
Foo y = "abd"; // Error: no one-step implicit conversion of UDTs






要解决您的编辑:要理解赋值运算符,只需将它分成几部分。假设 Foo 有明显的 operator =(const Foo& rhs)。我们可以说 x = y; ,它直接用 rhs 直接调用操作符 y 。现在考虑这个:


To address your edit: To understand the assignment operator, just break it up into parts. Suppose Foo has the obvious operator=(const Foo & rhs). We can say x = y;, which just calls the operator directly with rhs being y. Now consider this:

x = "abc";              // error, no one-step implicit conversion
x = std::string("abc"); // fine, uses Foo(std::string), then copy
x = Foo("abc");         // fine, implicit char(&)[4] -> const char* -> std::string, then as above

这篇关于在堆栈上声明一个对象的两种方式之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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