C++ Instance Initialization Syntax(C++ 实例初始化语法)
问题描述
给定这样的课程:
class Foo {
public:
Foo(int);
Foo(const Foo&);
Foo& operator=(int);
private:
// ...
};
这两行是完全等价的,还是它们之间有细微的差别?
Are these two lines exactly equivalent, or is there a subtle difference between them?
Foo f(42);
Foo f = 42;
<小时>
我通过在原始问题中使 Foo 构造函数显式"来混淆问题.我已将其删除,但感谢您的回答.
I confused matters by making the Foo constructor "explicit" in the original question. I've removed that, but appreciate the answers.
我还添加了复制构造函数的声明,以明确复制可能不是一个简单的操作.
I've also added declaration of a copy constructor, to make it clear that copying may not be a trivial operation.
我真正想知道的是,按照C++标准,Foo f = 42"会直接调用Foo(int)构造函数,还是会调用拷贝构造函数?
What I really want to know is, according to the C++ standard, will "Foo f = 42" directly call the Foo(int) constructor, or is the copy constructor going to be called?
看起来 fasih.ahmed 有我正在寻找的答案(除非它是错误的).
It looks like fasih.ahmed has the answer I was looking for (unless it's wrong).
推荐答案
Foo f = 42;
此语句将为值42"创建一个临时对象.
This statement will make a temporary object for the value '42'.
Foo f(42);
该语句将直接赋值,因此少了一个函数调用.
This statement will directly assign the value so one less function call.
这篇关于C++ 实例初始化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 实例初始化语法
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
