这几乎是一个重复的问题,但我真的不明白另一个给出的答案,所以我将再试一次:
我正在学习C++,并试图理解创建和使用构造函数的各种选项.所以我的第一个问题是这两个对象创建之间的区别是什么:
class Example{
Example(int x){myX = x} ;
private:
int myX;
}
Run Code Online (Sandbox Code Playgroud)
然后在我的主要方法:
Example example1 = new Example(5);
Example example2 = Example(5);
Example example3(5);
Run Code Online (Sandbox Code Playgroud)
我知道using new会给我一个动态分配的对象,我稍后需要删除它.并且example2将在堆栈上分配,不应该被删除.但我真的不明白何时或为什么要使用构造函数的样式example3.任何涉及最小术语的帮助都会非常感激,因为这就是为什么我似乎无法在别处理解这一点.非常感谢您提供的任何光线,你们可以为我提供这些.
这两个声明
Example example2 = Example(5);
Example example3(5);
Run Code Online (Sandbox Code Playgroud)
是等价的.虽然第一个看起来可能会创建一个对象,然后调用复制构造函数,但大多数编译器只是简单地创建example2对象.
关于何时选择使用上述哪种款式的决定在很大程度上取决于品味.
这是一个完整的示例程序来演示:
#include <iostream>
using namespace std;
class Test {
public:
Test(int x): X(x) {
cout << "constructor " << X << endl;
}
Test(const Test &rhs): X(rhs.X) {
cout << "copy " << X << endl;
}
Test &operator=(const Test &rhs) {
X = rhs.X;
cout << "assign " << X << endl;
return *this;
}
private:
int X;
};
int main()
{
Test t1 = Test(1);
Test t2(2);
t2 = t1;
}
Run Code Online (Sandbox Code Playgroud)
和输出(gcc 4.2.1,OS X Lion):
constructor 1
constructor 2
assign 1
Run Code Online (Sandbox Code Playgroud)
注意如何仅为t2 = t1(如预期的那样)调用赋值运算符,但根本不调用复制构造函数.(但是,正如Dennis Zickefoose在评论中指出的那样,复制构造函数必须是可访问的.尝试private在上面的示例中创建复制构造函数,编译器应该拒绝编译它.)
编辑:请注意,gcc实际上有一个控制此行为的选项:
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a
temporary which is only used to initialize another object of the
same type. Specifying this option disables that optimization, and
forces G++ to call the copy constructor in all cases.