I have this program
#include <iostream>
#include <memory>
using namespace std;
class B {
public:
void printB() {
cout << __FUNCTION__ << endl;
cout << mModuleName << endl;
}
void setModuleName() {
mModuleName = "BBBBBBB";
}
private:
string mModuleName;
};
class A {
public:
void printA() {
cout << __FUNCTION__ << endl;
b.printB();
}
B b;
};
int main(int argc, char ** argv) {
cout << " START " << endl;
std::shared_ptr<A> a;
a->printA();
a = std::make_shared<A>();
cout << " END " << endl;
return 0;
}
Here is the output:
vagrant@vagrant:~/development$ ./a.out
START
printA
printB
Segmentation fault (core dumped)
This obviously crashes when reaching to line where he tries to access mModuleName. I can fix it by moving printA() after make_shared line but I would like more robust solution to prevent SIGSEGV. Any suggestions?
This isn't an actual problem, you're simply doing something that is obviously going to crash because you are dereferencing a null pointer.
You can do this as an alternative and call make_shared
in the same line you declare the object.
int main(int argc, char ** argv) {
std::shared_ptr<A> a = std::make_shared<A>();
a->printA();
return 0;
}
There is no real reason to split up the object declaration and initialization in this case.
I can fix it by moving printA() after make_shared line but I would like more robust solution to prevent SIGSEGV. Any suggestions?
One possible method is to use a non-member function.
namespace MyApp
{
void print(A* aptr)
{
if ( aptr != nullptr )
{
aptr->printA();
}
}
}
and in main
use
MyApp::print(a);
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.