指针对象成员的访问冲突
所以我正在编写这个客户端/服务器程序。这段代码来自客户端。客户端有一个对象的实例
mpqs_sieve *instance_;
我将其作为指针的原因是,mpqs_sieve 只有一个带有 3 个参数的构造函数,我想在稍后的时间点实例化它。
客户端首先从服务器获取一些数据,并使用它来实例化instance_。此后,它将请求更多数据,并在收到此数据后(这些是二次多项式的三个系数),它应该在 instance_ 对象中设置这些数据。然而,在调用instance_的成员函数时,我在该函数调用中遇到了对instance_的成员之一的访问冲突。
我在这里发布了我的代码:在pastebin上,我在第100行收到错误。调用来自第71行,以及第 21 行之前。以下是摘录:
class client_protocol {
public:
static std::string parse_message(
network_message& msg, mpqs_sieve *instance_)
{
// ...
return set_mpqs_data(m.substr(i+1), instance_);
}
private:
static std::string set_mpqs_data(
std::string data, mpqs_sieve *instance_)
{
instance_ = new mpqs_sieve(n, M, FB_count);
// ...
}
};
有解决此问题的想法吗?
So I am coding this client/server program. This code is from the client side. The client has an instance of an object
mpqs_sieve *instance_;
The reason I make it as a pointer is, that mpqs_sieve only has a constructor that takes 3 arguments, and I want to instantiate it at a later point in time.
The client first gets some data from the server, and uses this to instantiate instance_. After this, it will request some more data, and upon receiving this (these are three coefficients for a quadratic polynomial), it should set these in the instance_ object. However upon calling a member function of instance_, I get an access violation on one of the members of instance_ within that function call.
I posted my code here: on pastebin, and I get the error on line 100. The call comes from line 71, and before that line 21. Here's an excerpt:
class client_protocol {
public:
static std::string parse_message(
network_message& msg, mpqs_sieve *instance_)
{
// ...
return set_mpqs_data(m.substr(i+1), instance_);
}
private:
static std::string set_mpqs_data(
std::string data, mpqs_sieve *instance_)
{
instance_ = new mpqs_sieve(n, M, FB_count);
// ...
}
};
Any ideas to solve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在将
instance_
指针的副本传递给函数,而不是对变量的引用。当您分配给instance_
时,您正在修改局部变量,而不是同名的成员变量。将函数参数更改为
mpqs_sieve *&instance_
。You are passing a copy of the
instance_
pointer to the function, not a reference to the variable. When you assign toinstance_
, you're modifying a local variable, not the member variable with the same name.Change the function parameter to
mpqs_sieve *&instance_
.关于现有答案中变量引用的注释是一个很好的观点,我还看到了另一个潜在问题:
如果我正确理解了您的代码,则该对象将在第 48 行的 set_mpqs_data() 函数中创建。您确定 set_mpqs_data( ) 函数在此时间之前被调用(正在处理 MPQS_DATA 消息)?否则,当您调用 set_polynomial_data() 时,instance_ 可能不会指向真实对象。
The note about references to variables in the existing answer is a good point, and I see one other potential issue:
If I understand your code correctly, the object gets created in the set_mpqs_data() function on line 48. Are you sure the set_mpqs_data() function is getting called before that time (the MPQS_DATA message is being handled)? Otherwise instance_ might not point at a real object when you call set_polynomial_data().