Mac*_*LCM 1 c++ constructor struct scope class
我有一个类,在实例化时我会构建两个标准结构成员。我的实例化是独立的,并且每次我构建一个实例时都在它自己的内存空间中,就像名称成员一样,但是构造函数中构建的结构每次都被赋予相同的内存地址,从而覆盖先前的实例化结构?指针和结构在任何地方都是静态的,所以我不明白为什么会发生这种情况。如果有人能发现我的错误,请指出。
-------------signal.h--------------
prama once
struct GenParams
{
float a;
float b;
};
class signal {
public:
signal();
~signal();
std::string sigName;
GenParams* mGP; //not static so every instance should have its own mGP I set to private as well but made no difference.
};
--------------------siganl.cpp------------------
#include signal.h
signal::signal()
{
GenParams GP; //every instance should have its own member GP at a unique mem location
// but instead GP is created at the same mem location
mGP = &GP; // mGP points to the same mem location every time the constructor is called
//fill struct with default values
GP.a = 0.0;
GP.b = 5.0;
}
signal::~signal()
{ }
--------------------interface.h--------------------
#include signal.h
class interface
{
public:
interface();
~interface();
std::string interName;
std::vector<signal*> sigList;
interface* iPtr;
unsigned int sigNum;
void newSignal();
--------------------------------interface.cpp----------------------
#include interface.h
interface::interface() : iPtr(this)
{ sigNum = 0;}
interface::~interface()
{
for (auto i : sigList)
delete i;
}
interface::newSignal()
{
signal* s = new signal;
//after this line returns the values are stored correctly in memory of struct
//during this line which does not reference the struct or the signal yet I see the structs
// memory get deallocated and go red as if something is writing to it and the values are gone
std::string newSName = this->interName + "sig" std::to_string(sigNum + 1);
//Here some values go back into the struct but they are bogus vals
s->sigName = newSName;
sigList.push_back(s);
//after adding to the list the sig instance has a name correctly written by the line above
//and a pointer it it but the pointer to the struct member mGP all instances point to the
//same memory location?? I don't understand how this is happening.
sigNum++;
}
Run Code Online (Sandbox Code Playgroud)
此构造函数调用未定义的行为
signal::signal()
{
GenParams GP; //every instance should have its own member GP at a unique mem location
// but instead GP is created at the same mem location
mGP = &GP; // mGP points to the same mem location every time the constructor is called
//fill struct with default values
GP.a = 0.0;
GP.b = 5.0;
}
Run Code Online (Sandbox Code Playgroud)
因为数据成员mGP
mGP = &GP;
Run Code Online (Sandbox Code Playgroud)
设置为GP具有自动存储方向的局部变量的地址
GenParams GP;
Run Code Online (Sandbox Code Playgroud)
退出构造函数后将不再存在。
因此数据成员mGP将具有无效值。
您应该动态分配该类型的对象GenParams或拥有该类型的数据成员。
注意这一行
std::string newSName = this->interName + "sig" std::to_string(sigNum + 1);
Run Code Online (Sandbox Code Playgroud)
有一个错字。看来你的意思是
std::string newSName = this->interName + "sig" + std::to_string(sigNum + 1);
Run Code Online (Sandbox Code Playgroud)