Why can't I use the vector? Is it not initialized? can't I access the member data in a static function?
#include<iostream>
#include<boost/thread.hpp>
#include<vector>
#include<boost/asio.hpp>
#include <ctime>
#include <string>
using boost::asio::ip::tcp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class maintain_overlay{
public:
maintain_overlay():thread_(&maintain_overlay::member_list_server)
{
thread_.join();
}
static void member_list_server(){
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
for (;;)
{
tcp::socket socket(io_service);
acceptor.accept(socket);
member_list.push_back(socket.remote_endpoint());
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
boost::asio::write(socket, boost::asio::buffer(message),
boost::asio::transfer_all(), ignored_error);
}
}
private:
std::vector<tcp::endpoint> member_list;
boost::thread thread_;
};
-----edit---
my server wants to maintain a list of all the incoming tcp conections? What is the best way to do this? Should I declare member_list static? When I do that I get an error error LNK2001: unresolved external symbol
member_list
is not a static
variable and is being accessed in the static
member function member_list_server()
. member_list
can only be accessed via an instance of maintain_overlay
.
Example fix using boost::bind
(which Andy posted first, as I had to compile and be certain before posting):
maintain_overlay() :
thread_(boost::bind(&maintain_overlay::member_list_server, this))
void member_list_server(){
Your member_list_server()
function is static, and you are trying to access a data member.
That would only be possible if your member function were not static, so that it would receive an implicit this
pointer on which to access the member_list
data member.
You should make your function non-static and use boost::bind()
when constructing your thread
object:
#include <boost/bind.hpp>
maintain_overlay()
:
thread_(boost::bind(&maintain_overlay::member_list_server, this))
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
thread_.join();
}
void member_list_server() {
// ...
}
Alternatively, if that is appropriate for the semantics of your class, you may make member_list
a static data member. In that case, do not forget to provide a definition for it at namespace scope:
class maintain_overlay
{
// ...
private:
static std::vector<tcp::endpoint> member_list; // DECLARATION
// ^^^^^^
};
std::vector<tcp::endpoint> maintain_overlay::member_list; // DEFINITION
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.