c++ - 在 C++ 中创建一个类对象

标签 c++ class

首先我来自 JAVA。

在java中我们创建这样的类对象。

Example example=new Example();

Example 类可以有构造函数,也可以不能有构造函数。

我可以像这样在 c++ 中使用它

Example* example=new Example();

构造函数是强制性的。

从本教程 http://www.cplusplus.com/doc/tutorial/classes/

我知道我们可以创建这样的对象。

Example example;

不需要构造函数。

我有两个问题。

  1. 这两种创建类对象的方式有什么区别。

  2. 如果我正在创建像 Example example 之类的对象; 如何在单例类中使用它。

就像我通常做的那样。

Sample* Singleton::get_sample() {
    if (sample == NULL) {
        sample = new Sample();
    }
    return sample;
}

如果我错了,请指导我。

最佳答案

I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorial I got that we can create object like this [...] Which do not require an constructor.

这是错误的。构造函数必须存在才能创建对象。如果您不提供任何构造函数,编译器在某些条件下可以隐式定义构造函数,但如果您希望实例化对象,最终构造函数必须存在。事实上,对象的生命周期被定义为在构造函数例程返回时开始。

来自 C++11 标准的第 3.8/1 段:

[...] The lifetime of an object of type T begins when:

— storage with the proper alignment and size for type T is obtained, and

— if the object has non-trivial initialization, its initialization is complete.

因此,必须存在构造函数。

1) What is the difference between both the way of creating class objects.

当您实例化具有自动存储持续时间的对象时,像这样(其中 X 是某个类):

X x;

您正在创建一个对象,当它超出范围时将自动销毁。另一方面,当你这样做时:

X* x = new X();

您正在动态创建一个对象,并将其地址绑定(bind)到一个指针。这样,当您的 x 指针超出范围时,您创建的对象不会被销毁。

在现代 C++ 中,这被认为是一种可疑的编程实践:尽管指针很重要,因为它们允许实现 reference semantics , raw 指针是不好的,因为它们可能导致内存泄漏(对象超过其所有指针并且永远不会被销毁)或悬空指针(指针超过它们指向的对象,可能导致取消引用时的未定义行为)。

事实上,当用new创建一个对象时,你总是必须记住用delete来销毁它:

delete x;

如果您需要引用语义并且被迫使用指针,在 C++11 中您应该考虑使用 智能指针:

std::shared_ptr<X> x = std::make_shared<X>();

智能指针负责处理内存管理问题,这让您对原始指针感到头疼。事实上,智能指针几乎与 Java 或 C# 对象引用相同。 “几乎”是必要的,因为程序员必须注意不要通过拥有智能指针来引入循环依赖。

2) If i am creating object like Example example; how to use that in an singleton class.

你可以这样做(简化代码):

struct Example
{
    static Example& instance()
    {
        static Example example;
        return example;
    }

 private:

    Example() { }
    Example(Example const&) = delete;
    Example(Example&&) = delete;
    Example& operator = (Example const&) = delete;
    Example& operator = (Example&&) = delete;

};

关于c++ - 在 C++ 中创建一个类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15310846/

相关文章:

Python 类——可变性

c++ - 在C中的txt文件的同一行中写入不同的用户输入数据

c++ - 程序正在打印意外的空行

c++ - Qt:使用鼠标将 QGraphicsItem (boundingRect()) 的大小调整为 QGraphicsScene

c++ - 表面上等效的表达式 (class)A a; 和 (class)A a{}; 之间的区别

python - 为什么这个实例成员在 Python 中实例化后无法访问?

c++ - 是否可以在编译时打印出 C++ 类的大小?

C++:指向具有不同类型参数的函数的函数指针 vector

c++ - 为什么调用析构函数

python - 定义类覆盖的问题 (__not__)