c++ main() brain teaser - c++

Can you think of a situation where your program would crash without reaching the breakpoint which you set at the beginning of main()?
My answer is during the initialization of static variables, but not sure...

THe above examples are true, but in my experience it's usually due to some problem loading a DLL...

A very simple example
struct abc
{
abc()
{
int* p = 0;
*p = 42; // Drat!
}
};
abc obj;
int main(){}

My answer gives 100% guarantee that this will crash before main().
#include <exception>
struct A
{
A()
{
std::terminate(); //from <exception>
//you can also call std::abort() from <cstdlib>
}
};
A a;
int main(){}
Demo : http://www.ideone.com/JIhcz
Another solution:
struct A
{
A()
{
throw "none";
}
};
A a;
int main(){}
Demo : http://www.ideone.com/daaMe

Related

Exception in aggregate initialization

In C++14 (gcc 6.3) I have the following code:
#include <memory>
#include <vector>
#include <stdexcept>
struct A
{
int a1;
int a2;
};
struct B
{
int b1;
std::shared_ptr< std::vector<A> > Alist;
};
struct C
{
std::shared_ptr<B> b;
std::shared_ptr< std::vector<A> > Alist;
};
std::shared_ptr< std::vector<A> > makeListA()
{
std::vector<A> toto = {{0,1}, {2,3}};
return std::make_shared< std::vector<A> >(toto);
}
std::shared_ptr< std::vector<A> > makeListAWithException()
{
throw std::out_of_range("My exception");
}
std::shared_ptr<B> makeB()
{
return std::make_shared<B>(B{0, makeListA()});
}
main()
{
std::make_unique<C>(C{makeB(),makeListAWithException()});
}
When running valgrind i have a memory leak : it looks like the objects created by "makeB()" function were not freed. I had this problem only when using aggregate initialization with curly braces.
When I define an explicit constructor on each class (A, B and C), I don't have this issue.
What am I doing wrong ?
Best regards
This is gcc bug 66139. Here is a short reproduction, courtesy of Andrzej (with a more thorough description available in the blog post):
#include <cstdio>
#include <stdexcept>
struct Resource
{
explicit Resource(int) { std::puts("create"); }
Resource(Resource const&) { std::puts("create"); }
~Resource() { std::puts("destroy"); }
};
Resource make_1() { return Resource(1); }
Resource make_2() { throw std::runtime_error("failed"); }
struct User
{
Resource r1;
Resource r2;
};
void process (User) {}
int main()
{
try {
process({make_1(), make_2()});
}
catch (...) {}
}
This prints:
create
It should print (as clang, correctly, does):
create
destroy
You don't have associated try/catch so your program terminate.
stack unwinding is not required in that case.
Following should solve your possible leak.
int main()
{
try
{
std::make_unique<C>(C{makeB(), makeListAWithException()});
}
catch (...)
{
}
}
if you change to like below, i think the problem is fixed
std::make_unique<C>(C{makeB(),makeListAWithException()});
to
auto b = makeB();
std::make_unique<C>(C{b,makeListAWithException()});

How to catch exception originating from constructor of statically allocated object?

How can catch an exception being thrown from the constructor of a statically allocated object? Or at least how I can handle such an exception (like set_terminate or smth.) to perform some teardown logic before termination:
#include <iostream>
struct A
{
A(){throw std::exception();}
};
static A a;
int main(){}
The general work around for having global variables is a function with a static member.
#include <iostream>
struct A
{
A(){throw std::exception();}
};
A& getA()
{
static A a;
return a;
}
int main()
{
try {
getA();
}
catch(...) {
// error
}
}
Now You still effectively have a global variable. BUT the variable is initialized on first use. If you do this for all globals then the globals will not be initialized before main starts and you can out the try catch in main().

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

Pointer to a different instance.

How can such a code work correctly when the IWindow pointer clearly has an address to a ISheet class which has no method Say?
#include <iostream>
using namespace std;
class IWindow
{
private:
int p;
double f;
public:
void Say() { cout << "Say in IWindow"; }
};
class ISheet
{
public:
void foo() { cout << "ISheet::foo"; }
};
int main()
{
ISheet *sh = new ISheet();
int ptr = (int)sh;
IWindow *w = (IWindow*)ptr;
w->Say();
sh->foo();
return 0;
}
When compiled in Visual Studio 2015 it runs and executes with no problems, but I was expecting to get an error on line w->Say(). How is this possible?
It works by the grace of the almighty Undefined Behavior. Your functions don't try to access any data members of the containing class, they just write something to std::cout, which anyone can do.
What you've effectively done is
#include <iostream>
void IWindow_Say(void*)
{
std::cout << "Say in IWindow";
}
int main()
{
IWindow_Say(0xdeadbeef); // good luck with that pointer
}
You never used the pointer (which became this in your original example) so no side-effects were observed.

C++ function in main doesn't work

Why doesn't this code print the letter a?
#include <iostream>
#include <stack>
void a()
{
std::cout<<"a";
}
int main ()
{
void a();
return 0;
}
You're accidentally declaring a function inside main() instead of calling it.
int main ()
{
void a(); // <-- DECLARES a function, does not call it
return 0;
}
Here is the fix:
int main ()
{
a();
return 0;
}
Also note that you probably want a newline:
void a()
{
std::cout<<"a\n";
}
Or you can use std::endl, if you like typing.
You're declaring your function twice:
#include <iostream>
#include <stack>
void a()
{
std::cout<<"a";
}
int main ()
{
void a(); // this is a declaration
return 0;
}
Do this instead:
int main ()
{
a(); // this is a function call, which will execute your function
return 0;
}
Its ok qwertyu uytrewq, everyone have these kind of problems in start, the main thing is never hesitate to question.
The main error in your code is, that you are declaring the function but not calling it. There are three phases of functions.
Declaration i.e
void a();
Definition i.e
void a ()
{
std::cout << "a";
}
Calling a Function i.e
a();
Now the major error in your program belongs to the 3rd phase (Calling a Function) you are mentioning the function type also which is know as Deceleration, so the correct code is as following.
#include <iostream>
#include <stack>
void a()
{
std::cout<<"a";
}
int main ()
{
a();
return 0;
}
In your main function:
int main()
{
// Don't add Void
a();
return 0;
}