bind shared_from_this the memory will not be released - c++

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/enable_shared_from_this.hpp>
class A: public boost::enable_shared_from_this<A>
{
typedef boost::function<int()> GET;
public:
A()
{
std::cout << "A::A() " << this << std::endl;
}
~A()
{
std::cout << "A::~A()" << this <<std::endl;
}
void set()
{
myget=boost::bind(&A::get, shared_from_this());
}
Here is the problem: it will not be released when I bind it with with shared_from_this(). But if I bind it with this (boost::bind(&A::get, this)), the instance will be released.
int getI()
{
myget();
}
inline int get()
{
return 1;
}
private:
GET myget;
};
void test()
{
boost::shared_ptr<A> a(new A);
a->set();
a->getI();
}
int main()
{
test();
return 0;
}
My question is: why the instance of A is never released even if the program have been shut down?

The problem is that the myget variable prevents the destructor from ever running.
So you can't even do
~A() {
std::cout << "A::~A()" << this << std::endl;
myget = {};
}
This is what weak-pointers have been invented for. In this particular case though, you could simply use this as there is no way that myget can be accessed after the lifetime of A

Related

In c++, How can I share data between two classes efficiently?

#include "dataConsumer.h"
#include <iostream>
#include <Windows.h>
DataConsumer::DataConsumer(){}
DataConsumer::~DataConsumer(){}
void DataConsumer::Body()
{
std::cout << "DataConsumer Start" << std::endl;
while (1)
{
//I want to get providerData_ of DataProvide class in here
Sleep(1000);
}
}
#include "dataProvider.h"
#include <iostream>
#include <Windows.h>
DataProvider::DataProvider(){}
DataProvider::~DataProvider(){}
void DataProvider::Body()
{
std::cout << "DataProvider Start" << std::endl;
while (1)
{
//Update data in here
providerData_++;
Sleep(1000);
}
}
There are two classes.
And I want to get providerData_ of dataProvider class in dataConsumer class.
To resolve this situation, I thought the following is one solution.
I made singleton dataTransfer class like below.
But I am not sure whether this is a general solution in c++.
First of all, I want to know whether my solution is available.
To the next, If you know the better solution(or design pattern) to resolve my situation, please advise to me.
#ifndef DATATRANSFER_H
#define DATATRANSFER_H
class DataTransfer
{
public:
static DataTransfer* getInstance()
{
static DataTransfer instance;
return &instance;
}
void GetData(unsigned int *data)
{
if(data)
*data = data_;
}
void SetData(unsigned int *data)
{
if(data)
data_ = *data;
}
private:
DataTransfer(){}
~DataTransfer(){}
unsigned int data_;
};
#endif
#include "dataConsumer.h"
#include "dataTransfer.h"
#include
#include
DataConsumer::DataConsumer(){}
DataConsumer::~DataConsumer(){}
void DataConsumer::Body()
{
unsigned int data = 0;
std::cout << "DataConsumer Start" << std::endl;
while (1)
{
//I want to get providerData_ of DataProvide class in here
DataTransfer::getInstance()->GetData(&data);
std::cout << "DataConsumer data:" << data << std::endl;
Sleep(1000);
}
}
#include "dataProvider.h"
#include "dataTransfer.h"
#include
#include
DataProvider::DataProvider() : providerData_(0)
{
}
DataProvider::~DataProvider(){}
void DataProvider::Body()
{
std::cout << "DataProvider Start" << std::endl;
while (1)
{
//Update data in here
providerData_++;
DataTransfer::getInstance()->SetData(&providerData_);
Sleep(1000);
}
}
If both classes need to be able to get and set the providerData_, I would create a third Data class to own the providerData_.
Then I could give a pointer of the Data class to all the classes that needed access to that data.
There are 3 patterns called aggregation, composition and association in software architecture.
The pattern in which class Foo can use class Bar but does not "own" it and both classes remain independent is Association.
DataConsumer have a pointer to DataProvider :
// Association
class DataConsumer{
private:
DataProvider* provider;
public:
void setProvider(DataProvider* p) { provider = p; }
void Body();
int /* or whatever data type */ getData()
{
if(provider != nullptr)
{
return provider->getData();
}
else
{
// handle provider not being set
return ...;
}
}
};
DataProvider must be allocated / created outside of DataConsumer and is independent.
Read this answer and this answer for a better explanation on these pattern.

Does std::future support polymorphism?

Does std::future in c++ support polymorphism?
So, if to store child_class in future<parent_class>, can I after get it after by dynamic_cast<child_class>?
Providing you use a reference or a pointer (probably obvious since it'll fail to compile otherwise)... Yes.
#include <iostream>
#include <future>
using namespace std;
struct Parent {
virtual void a() { cout << "I am parent"; }
};
struct Child : Parent {
virtual void a() { cout << "I am child"; }
};
Child g_c; //just some global for the purposes of the example
int main() {
std::future<Parent&> p = async(launch::async, []() -> Parent& { return g_c; });
auto c = dynamic_cast<Child&>(p.get());
c.a();
return 0;
}
code result here: http://ideone.com/4Qmjvc

How to invoke a C++ function after main() finishes

I am developing a C++ tool that should run transparent to main program. That is: if user simply links the tool to his program the tool will be activated. For that I need to invoke two functions, function a(), before main() gets control and function b() after main() finishes.
I can easily do the first by declaring a global variable in my program and have it initialize by return code of a(). i.e
int v = a() ;
but I cannot find a way to call b() after main() finishes?
Does any one can think of a way to do this?
The tool runs on windows, but I'd rather not use any OS specific calls.
Thank you, George
Use RAII, with a and b called in constructor/destructor.
class MyObj {
MyObj()
{
a();
};
~MyObj()
{
b();
};
};
Then just have an instance of MyObj outside the scope of main()
MyObj obj;
main()
{
...
}
Some things to note.
This is bog-standard C++ and will work on any platform
You can use this without changing ANY existing source code, simply by having your instance of MyObj in a separate compilation unit.
While it will run before and after main(), any other objects constructed outside main will also run at this time. And you have little control of the order
of your object's construction/destruction, among those others.
SOLUTION IN C:
have a look at atexit:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void bye(void)
{
printf("That was all, folks\n");
}
int main(void)
{
long a;
int i;
a = sysconf(_SC_ATEXIT_MAX);
printf("ATEXIT_MAX = %ld\n", a);
i = atexit(bye);
if (i != 0) {
fprintf(stderr, "cannot set exit function\n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
http://linux.die.net/man/3/atexit
this still implies however that you have access to your main and you can add the atexit call. If you have no access to the main and you cannot add this function call I do not think there is any option.
EDIT:
SOLUTION IN C++:
as sudgested there is a c++ equivalent from std. I simply paste in here an example which i copied from the link available just below the code:
#include <iostream>
#include <cstdlib>
void atexit_handler_1()
{
std::cout << "at exit #1\n";
}
void atexit_handler_2()
{
std::cout << "at exit #2\n";
}
int main()
{
const int result_1 = std::atexit(atexit_handler_1);
const int result_2 = std::atexit(atexit_handler_2);
if ((result_1 != 0) or (result_2 != 0)) {
std::cerr << "Registration failed\n";
return EXIT_FAILURE;
}
std::cout << "returning from main\n";
return EXIT_SUCCESS;
}
http://en.cppreference.com/w/cpp/utility/program/atexit
Isn't any global variable constructed before main and destructed afterward? I made a test struct whose constructor is called before main and the destructor afterward.
#include <iostream>
struct Test
{
Test() { std::cout << "Before main..." << std::endl; }
~Test() { std::cout << "After main..." << std::endl; }
};
Test test;
int main()
{
std::cout << "Returning now..." << std::endl;
return 0;
}
If you're happy to stick with a single compiler and non-standard C/C++, then GCC's __attribute__((constructor)) and __attribute__((destructor)) might be of use:
#include <stdio.h>
void __attribute__((constructor)) ctor()
{
printf("Before main()\n");
}
void __attribute__((destructor)) dtor()
{
printf("After main()\n");
}
int main()
{
printf("main()\n");
return 0;
}
Result:
Before main()
main()
After main()
Alternatively to the destructor, you can use atexit() in a similar manner - in C++, you do not need to have access to main() to register atexit there. You can do that as well it in your a() - for example:
void b(void) {
std::cout << "Exiting.\n";
}
int a(void) {
std::cout << "Starting.\n";
atexit(b);
return 0;
}
// global in your module
int i = a();
That being said, I'd also prefer the global C++ class object, which will call the b() stuff in its destructor.

Any Example that Prove Initializer List Call before Constructor C++

I have searched but still didn't get easy and proper answer, Below is my code.
#include <iostream>
using namespace std;
class Parent
{
private:
int a;
public:
Parent():a(3) { cout << a; }
};
int main()
{
Parent obj;
return 0;
}
Can you add additional lines of code that can prove or show me that initializer list call before constructor?
I would modify you code ever so slightly:
#include <iostream>
using namespace std;
class Parent
{
public:
int a;
public:
Parent():a(3){
a = 4;
}
};
int main()
{
Parent obj;
cout << obj.a;
return 0;
}
The output is 4, thus a was initialized with 3 and then assigned 4.
Simply add data member, which has constructor, which prints something. Example:
#include <iostream>
using namespace std;
struct Data {
Data(int a) {
cout << "Data constructor with a=" << a << endl;
}
};
class Parent
{
private:
Data a;
public:
Parent():a(3){
cout << "Parent constructor" << endl;
}
};
int main()
{
Parent obj;
return 0;
}
Output:
Data constructor with a=3
Parent constructor
Conclusion: Data constructor was called before constructor body of Parent.
You don't get variable "a" value 10 in this program , a assigned before constructor method called .
#include<iostream>
using namespace std;
class Test
{
public:
int a,b;
public:
Test():a(b){
b=10;
}
};
int main()
{
Test obj;
cout<<"a :"<<obj.a<<" b:"<<obj.b;
return 0;
}
This is best shown with multiple classes:
#include <iostream>
class A
{
public:
A()
{
std::cout << "Hello World!" << std::endl;
}
};
class B
{
private:
A* a;
public:
// Call a's constructor
B():a(new A)
{
// Some code
}
~B()
{
delete a;
}
};
int main()
{
B obj;
return 0;
}

How can I access my class instance from a boost thread?

I have the following code (this is some semi-sudo code, which may not compile):
class FooBar {
public:
void a();
void b();
boost::shared_ptr<boost::thread> m_thread;
std::string m_test;
};
void FooBar::a() {
m_test = "Foo bar"
m_thread = shared_ptr<thread>(new thread(bind(&FooBar::b, this)));
}
void FooBar::b() {
cout << m_test;
}
The code cout << test does not yield any output, because m_test is "" instead of "Foo bar". Why is this? I thought that passing this as the 2nd argument to bind would allow me to access the same instance from b() - am I incorrect?
Yes, that works. Here's the "real" version, which does in fact print "Foo bar":
#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
using namespace boost;
struct FooBar {
void a();
void b();
shared_ptr<thread> m_thread;
std::string m_test;
};
void FooBar::a() {
m_test = "Foo bar";
m_thread = make_shared<thread>(bind(&FooBar::b, this));
}
void FooBar::b() {
std::cout << m_test;
}
int main() {
FooBar fb;
fb.a();
fb.m_thread->join();
return 0;
}
The code cout << test does not yield any output, because m_test is ""
I suspect this is because the object was being destroyed before the thread got around to evaluating the member variable. Note the join(), it's very important.