如何取消/不调用全局变量中的构造函数 [英] How do I cancel/not call the constructor in a global variable

查看:311
本文介绍了如何取消/不调用全局变量中的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请不要问为什么(TM)

Please don't ask why (TM)

为了乐趣,我想取消/不调用构造函数。这是一个示例代码。我不是'a'是一个指针。我想在main()中的语法是相同的(使用一个点而不是 - >)。我想使用'a'是我期望,但不调用构造函数。 A应该有分配给它的内存,所以我希望我可以调用一个在原地构造函数。

For fun i am trying to cancel/not call the constructor. This is an example code. I do -not- 'a' to be a pointer. I want the syntax in main() to be the same (using a dot rather than ->). I would like the usage of 'a' to be what i expect but not call the constructor. A should have memory allocated to it so at a time i desire i can call an in place constructor.

这不会在任何代码中使用!我只是想弄清楚如果它的可能!是否有一种方法我可以分配但不调用其构造函数?

This is not going to be used in any code! I am just trying to figure out if its possible! Is there a way i can allocate a but not call its constructor?

您可以更改如何定义或声明。我只需要语法相同。

You may change how A is defined or declared. I just need the syntax to be the same.

#include <cstdio>
struct A{ A(){printf("a"); regularDots=1; } int regularDots; };
A a;
int main(){ a.regularDots; }

使用工作语法处理代码,但由于某种原因它循环无限。

Heres code with working syntax however it loops infinite for some reason.

#include <cstdio>

template<class T>struct BlockOf{ char t[sizeof(T)]; operator T&() { return *this; } };
struct A{ A(){printf("a");} int regularDots; };
BlockOf<A> _a;
A&a=*&_a;

int main(){ a.regularDots=9;}


推荐答案

破坏前提条件和不变量不是一个好主意,这样做会使你在未定义行为的领域里。

Breaking preconditions and invariants is not a good idea, and doing so lands you squarely in the realm of undefined behavior.

你要求的是相对直接的:

That said, what you asked for is relatively straightforward:

A& a = *reinterpret_cast<A*>(new char[sizeof (A)]); // or malloc/calloc, as Christian said in a comment

/ p>

Or, in C++11

alignas(A) char ua[sizeof (A)];
A& a = reinterpret_cast<A&>(ua[0]);

或者如果你的编译器支持不确定大小的终端数组,你可以做这样的工作: http://ideone.com/EZexK

Or if your compiler supports terminal array of indeterminate size, you may be able to make something like this work: http://ideone.com/EZexK

一个更好的方法要为你的全局零初始化对象定义一个POD类型,然后通过继承或组合在你的类里面嵌入那个POD类型(像以前一样执行初始化)。

A much better approach would be to define a POD type for your global zero-initialized object, then embed that POD type in your class (which performs initialization as before), via either inheritance or composition.

这篇关于如何取消/不调用全局变量中的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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