c++ - C++ 构造函数语法的详细信息

标签 c++ constructor

这几乎是一个重复的问题,但我真的不明白另一个问题的答案,所以我要再试一次:

我正在学习 C++,并且试图了解用于创建和使用构造函数的各种选项。所以我的第一个问题是这两个对象创建之间的区别是什么:

 class Example{
      Example(int x){myX = x} ;
      private:
         int myX;
 }

然后在我的主要方法中:

 Example example1 = new Example(5);
 Example example2 = Example(5);
 Example example3(5);

我知道使用 new 会给我一个动态分配的对象,稍后我需要删除它。并且 example2 将分配在堆栈上,不需要删除。但是我真的不明白什么时候或者为什么要使用 example3 的构造函数样式。任何涉及最少行话的帮助将不胜感激,因为这就是为什么我在其他地方似乎无法理解这一点。非常感谢你们能为我提供任何帮助。

最佳答案

两个声明

Example example2 = Example(5);
Example example3(5);

是等价的。尽管第一个看起来可能会创建一个对象,然后调用复制构造函数,但大多数编译器只会在适当的位置创建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;
}

和输出(gcc 4.2.1,OS X Lion):

constructor 1
constructor 2
assign 1

注意赋值运算符是如何只为 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.

关于c++ - C++ 构造函数语法的详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7782343/

相关文章:

C++ std::ifstream 在构造函数中的问题

c++ - 声明一个没有内容的函数; - 然后是内容 {} - C++

c++ - 使用数组而不是 vector 合并排序实现

design-patterns - 单例模式中的私有(private)构造函数

构造函数中的 C++ 保护声明

Java - 子类调用 super 构造函数,它调用子类方法而不是它自己的方法

c++ - 没有 libeay32.dll 的 OpenSSL win32

c++ - 如何解决方法重载中的函数调用?

c++ - 为什么我在显式编写复制构造函数后得到垃圾值?

ruby - 当一个对象的构造函数构建另一个对象时 stub