为什么我不能从C ++中该类的实例调用该类的构造函数? [英] Why can I not call my class's constructor from an instance of that class in C++?

查看:118
本文介绍了为什么我不能从C ++中该类的实例调用该类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类的对象何时可以调用该类的析构函数,就好像它是常规函数一样?为什么不能将同一类的构造函数作为其常规函数之一调用?为什么编译器会阻止我们执行此操作?

When can an object of a class call the destructor of that class, as if it's a regular function? Why can't it call the constructor of the same class, as one of its regular functions? Why does the compiler stops us from doing this?

例如:

class c
{
public:
   void add() ;
   c();
   ~c() ;
};

void main()
{
 c objC  ;
 objC.add() ;
 objC.~c() ; // this line compiles
 objC.c() ;  // compilation error
}


推荐答案

按定义,构造函数在创建对象时仅被调用一次。如果您有权访问某个对象,则必须已创建该对象,因此不允许您再次调用构造函数-这就是不允许显式构造函数调用的原因。同样,销毁对象时,析构函数只能调用一次。如果这总是可以自动完成,那么该语言还将禁止显式的析构函数调用。

By definition, a constructor is only called once, when the object is created. If you have access to an object, then it must have been created, so you're not allowed to call the constructor again - this is the reason why explicit constructor calls are not allowed. Similarly, destructors must only be called once, when the object is destroyed. If this could always done automatically, then the language would also forbid explicit destructor calls.

但是,在某些情况下,您可能希望对内存管理进行精确控制,并希望能够在要管理的内存中显式创建和销毁对象。为此,该语言提供了 placement new以在任意位置创建对象,并且显式析构函数调用将销毁以此方式创建的对象。显式构造函数调用将无用,因为您需要能够指定新对象的位置-因此,您将获得 placement new。显式析构函数调用就足够了,因此不需要发明某种匹配的放置删除。

However, in some circumstances, you might want precise control over memory management, and the ability to explicitly create and destroy objects within memory that you are managing. For this purpose, the language provides "placement new" to create an object at an arbitrary location, and explicit destructor calls to destroy objects created this way. An explicit constructor call wouldn't be useful, since you need to be able to specify the location of the new object - so you get "placement new" instead. An explicit destructor call is sufficient, so there's no need to invent some sort of matching "placement delete".

因此:显式构造函数调用没有有效的用途,因此他们是不允许的。显式析构函数调用有一个有效用法,因此(在语法上)允许使用它们,其规则是,您只能在不会被破坏的对象(即使用 placement new创建的对象)上使用它们,情况下,请致电给他们一次。像许多C ++错误一样,以其他任何方式使用它们都会编译,但给出不确定的行为。

So: there is no valid use for explicit constructor calls, so they are not allowed. There is a valid use for explicit destructor calls, so they are (syntactically) allowed, with the rule that you must only ever use them on objects that won't otherwise be destroyed, i.e. objects created using "placement new", and in that case call them exactly once. Using them in any other way, like so many C++ errors, will compile but give undefined behaviour.

这篇关于为什么我不能从C ++中该类的实例调用该类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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