【发布时间】:2021-03-30 07:37:16
【问题描述】:
这是一个演示代码 sn-p(https://godbolt.org/z/31Tq3r):
#include<iostream>
class Ctx
{
public:
enum RUN_MOD
{
MOD_RT,
MOD_NRT,
};
Ctx(RUN_MOD runType)
{
if(runType == MOD_RT)
{
Ctx();
}
}
Ctx()
{
m_L = malloc(100);
std::cout << "set m_L=" << m_L << std::endl;
}
void print()
{
std::cout <<"print() m_L=" << m_L << std::endl;
}
private:
void *m_L;
const char* const ARG_TYPE_NOT_MATCH = "the type of argument is not match";
const char* const ARG_NUM_INVALID = "the number of arguments is invalid";
const char* const STACK_OPS_INPUT_ARG_INVALID = "the input argument passed to the stack ops is invalid";
};
int main()
{
Ctx ctx(Ctx::RUN_MOD::MOD_RT);
ctx.print();
}
以下是在 Ubuntu 上调用二进制程序时的输出:
set m_L=0x614c20
print() m_L=0x400ad0
你看地址不一样。我确实通过调用Ctx::Ctx()(由Ctx::Ctx(RUN_MOD runType) 调用)来设置m_L。我真的很困惑。
【问题讨论】:
-
我真的很困惑。 --
if(runType == MOD_RT) { Ctx();}-- 这不是你想的那样。 -
我想重用一个特定的ctor。这段代码 sn-p 仅用于演示。
-
您发布的代码是我们必须使用的,演示或不演示。那行代码不会“链接”下一个构造函数。
-
不要在 C++ 中使用
malloc。使用new。或者更好的是,使用std::unique_ptr。这样可以防止像现在这样的内存泄漏。 -
在构造函数中调用构造函数没有错。它会完全按照你告诉它的去做。在您的情况下,您告诉它创建一个新的本地对象并立即销毁它。 (Aldo 导致即时内存泄漏)
标签: c++ c++11 constructor