在具有局部变量的函数中设置类成员



嗨,我有这个例子。

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;
}

这样设置类成员变量有效吗?还是当int x=2超出范围时它是随机行为?!感谢您的帮助

另一个问题:在本例中,

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;
}

在void init class函数中创建本地AnotherClassRessource并将其作为参数传递以创建新的AnotherClass是否有效,或者它将是未定义的行为?!这确实取决于AnotherCLass是否在内部使用了指向AnotherClassRessource的引用或指针,不是吗。感谢您的帮助

是的,您的代码是有效的,下面是SetX(...)函数中发生的事情

void SetX(Test& test)
{ // Start a scope
int x = 2;    // Create a local variable on the stack named x, set it's value to 2
test.setX(x); // Pass the local variable by value (does a copy) to the member function setX(...)
} // Deallocate stack variables in this scope (local variable x deallocated here)

总之,在将值传递给setX(...)作为参数之前,您的局部变量x被分配了一个值(2(,这意味着x的值被复制到以下代码中的参数变量x

void setX(const int x) {m_x=x;}

解决您的问题:如果您的setX(...)成员函数获取并存储了对整数而不是值的引用,则不会起作用。这意味着对已释放堆栈变量的引用可以存储在类中(尽管已不存在(。

class Test
{
public:
void setX(int& x) {m_x=x;} // Notice the & for reference
...
private:
int& m_x; // Notice the & for reference
}

它肯定是有效的,尽管有一个方法来设置变量,然后有一个函数来调用该方法有点多余。

edit:您可能会问类的实例是否保留了您在函数中为其指定的值。这也是正确的,因为您通过引用传递实例。

如果我没有忽略某些内容,那么您的代码应该是有效的。如果要存储对变量的引用或指针,则只需担心超出范围的变量。

但是,由于m_x被定义为int,而不是int&int*,因此当您使用m_x=x;时,您可以在setX类方法中创建副本

因此,在函数返回后,值已经存储在类中,一切都很好。

最新更新