Hi i have this example.
class Test
{
public:
Test(){m_x = 0;};
~Test() {};
void setX(const int x) {m_x=x;}
int getX() const {return m_x;}
private:
int m_x;
};
void SetX(Test& test)
{
int x = 2;
test.setX(x);
}
int main()
{
Test X;
SetX(X);
std::cout << "XX: " << X.getX() << std::endl;
return 0;
}
Is it valid to set the class member variable like this or is it random behaviour when int x=2 goes out of scope?! Thanks for your help
Another question: In this example
class Test
{
public:
Test(){m_x = 0;};
~Test() {};
void init(const int x, const int y)
{
AnotherClassRessource res(x,y);
m_other.reset(new AnotherClass(res));
}
void doSomething()
{
m_other->doSomething();
}
private:
int m_x;
std::unique_ptr<AnotherClass> m_other;
};
int main()
{
Test X;
X.init(1,2);
X.doSomething();
return 0;
}
Is it valid in the void init class function to create a local AnotherClassRessource and pass it as argument to create a new AnotherClass or will it be undefinded behaviour?! It does depend if AnotherCLass uses internaly an reference or pointer to the AnotherClassRessource, doesnt it. Thanks for your help
m_xwas a reference. Note that right now you are actually assigning thexargument ofsetXfunction which goes out of scope even earlier, not local variablexofSetX.