I recently read simple STL sources,Here is the code:
#include <iostream>
#include <cstddef>
using namespace std;
class alloc
{
};
template <typename T, typename Alloc = alloc, size_t Bufsiz = 0>
class deque
{
public:
deque() { cout << "deque()" << endl; }
};
template <typename T, typename Sequence = deque<T> >
class stack
{
public:
stack() { cout << "stack()" << endl; }
private:
Sequence c;
};
int main()
{
stack<int> x;
return 0;
}
The output:
deque()
stack()
When i created a stack object,it should have called stack constructor first.But the fact is not.
Why the compiler calls deque constructor first?
Before you enter the body of a constructor, base class constructors are called, then all non-static member variables are default initialized in the order of declaration, unless they appear in a member initialization list. In your code Sequence c is initialized first and then the body of Stack::Stack() is executed.
This program illustrates the order of construction - destruction.
#include <iostream>
#include <string>
using namespace std;
struct Base_1
{
Base_1()
{
cout << "Base_1\n";
}
~Base_1()
{
cout << "~Base_1\n";
}
};
struct Base_2
{
Base_2()
{
cout << "Base_2\n";
}
~Base_2()
{
cout << "~Base_2\n";
}
};
struct Member_1
{
Member_1()
{
cout << "Member_1\n";
}
~Member_1()
{
cout << "~Member_1\n";
}
};
struct Member_2
{
Member_2()
{
cout << "Member_2\n";
}
~Member_2()
{
cout << "~Member_2\n";
}
};
struct Member_non_default
{
Member_non_default( string s )
{
cout << "Member non default\n";
}
~Member_non_default()
{
cout << "~Member non default\n";
}
};
struct Static_member
{
Static_member()
{
cout << "Static member\n";
}
~Static_member()
{
cout << "~Static member\n";
}
};
struct Derived: Base_1, Base_2
{
Member_1 m1;
Member_non_default m;
Member_2 m2;
static Static_member sm;
Derived():
m { "Member non default\n" }
{
cout << "Derived\n";
}
~Derived()
{
cout << "~Derived\n";
}
};
Static_member Derived::sm;
int main()
{
Derived d;
}
Output
Static member
Base_1
Base_2
Member_1
Member non default
Member_2
Derived
~Derived
~Member_2
~Member non default
~Member_1
~Base_2
~Base_1
~Static member
Related
A performance bottleneck of my program is frequent calls to functions like following update functions.
Given that flag parameter is always a bool literal, I want to "unroll" the update function to two versions, one with flag=true and one with flag=false, to avoid branch prediction failure.
for normal functions, a bool template parameter can solve this problem easily.
However, template cannot be applied to virtual functions.
I can create two virtual functions manually, but then I have to copy the long code part. It makes futher development harder.
Is there anyway allowing me to write two versions in one function, controlled by a compiling-time constant flag?
#include <iostream>
#include <random>
using std::cout;
using std::endl;
struct Base
{
virtual void update(bool flag) = 0;
};
struct Derived1 : public Base
{
void update(bool flag)
{
if (flag)
{
// some computations
cout << "Derived1 flag=true" << endl;
}
else
{
// some computations
cout << "Derived1 flag=false" << endl;
}
// long code containing several flag-conditioned blocks like the block above
cout << "Derived1" << endl;
}
};
struct Derived2 : public Base
{
void update(bool flag)
{
if (flag)
{
// some computations
cout << "Derived2 flag=true" << endl;
}
else
{
// some computations
cout << "Derived2 flag=false" << endl;
}
// long code containing several flag-conditioned blocks like the block above
cout << "Derived2" << endl;
}
};
int main()
{
Base *p;
srand(time(nullptr));
if (rand() % 2 == 1)
{
p = new Derived1();
}
else
{
p = new Derived2();
}
p->update(false);
p->update(true);
}
Unfortunately, there is no such thing as virtual templates. What can be done however is to create several virtual functions taking an integral (boolean in this particular case) constant, if the flag is really a compile time literal:
#include <iostream>
#include <random>
#include <type_traits>
#include <memory>
using std::cout;
struct Base
{
virtual void updateSeparate(std::true_type) = 0;
virtual void updateSeparate(std::false_type) = 0;
};
struct Derived1 : public Base
{
void updateSeparate(std::true_type)
{
cout << "Derived1 flag=true\n";
updateCommonImpl();
}
void updateSeparate(std::false_type)
{
cout << "Derived1 flag=false\n";
updateCommonImpl();
}
private:
void updateCommonImpl() //or just a static function inside implementation file if members are not used
{
cout << "Derived1\n";
}
};
struct Derived2 : public Base
{
void updateSeparate(std::true_type)
{
cout << "Derived2 flag=true\n";
updateCommonImpl();
}
void updateSeparate(std::false_type)
{
cout << "Derived2 flag=false\n";
updateCommonImpl();
}
private:
void updateCommonImpl() //or just a static function inside implementation file if members are not used
{
cout << "Derived2\n";
}
};
int main()
{
std::unique_ptr<Base> p;
srand(time(nullptr));
if (rand() % 2 == 1)
{
p = std::make_unique<Derived1>();
}
else
{
p = std::make_unique<Derived2>();
}
p->updateSeparate(std::bool_constant<false>{});
p->updateSeparate(std::bool_constant<true>{});
}
DEMO
However, I cannot tell if that will help or maybe hinder the performance even more by making the vtable lookup time even longer, you have to experiment with that by yourself I'm afraid.
I tried to implement a CRTP pattern with constexpr template parameter, please take a look
template<typename T>
struct Base {
template<bool flag>
int update() {
return static_cast<T*>(this)->template updateImpl<flag>();
}
};
struct Derived1 : public Base<Derived1> {
template<bool flag>
constexpr int updateImpl() {
if constexpr (flag) {
return 1;
} else {
return 2;
}
}
};
struct Derived2 : public Base<Derived2> {
template<bool flag>
constexpr int updateImpl() {
return 3;
}
};
int main() {
auto obj1 = new Derived1();
std::cout << obj1->update<true>(); // 1
std::cout << obj1->update<false>(); // 2
auto obj2 = new Derived2();
std::cout << obj2->update<true>(); // 3
std::cout << obj2->update<false>(); // 3
}
Default constructor shouldn't zero out any data member. But in some situation, it seems not to be like this.
The code example is brief.
#include <iostream>
using namespace std;
class Foo {
public:
int val;
Foo() = default;
};
int main() {
Foo bar;
if (bar.val != 0) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
As excepted, above program outputs:
true
However, if a print statement for bar's data member added, the var member will be initialized to zero:
...
int main() {
Foo bar;
cout << bar.val << endl;
...
}
The outputs will be:
0
false
Similarly, if adding virtual function and destructor to the class Foo:
#include <iostream>
using namespace std;
class Foo {
public:
virtual void Print() {}
~Foo() {}
int val;
Foo() = default;
};
int main() {
Foo bar;
if (bar.val != 0) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
or just init bar object:
class Foo {
public:
int val;
Foo() = default;
};
int main() {
Foo bar = Foo();
...
}
outputs with:
false
So what‘s the cause that influence the data member value of class? Shouldn't all of this test outputs with true?
As default initialization in this case:
otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.
Note that indeterminate value includes 0, which is a valid result too. BTW reading these indeterminate values leads to UB.
In C ++, I first encountered function pointers.
I tried to use this to make it similar to Action and Delegate in C #.
However, when declaring a function pointer, it is necessary to specify the type of the class in which the function exists.
ex) void (A :: * F) ();
Can I use a function pointer that can store a member function of any class?
In general, function pointers are used as shown in the code below.
class A {
public:
void AF() { cout << "A::F" << endl; }
};
class B {
public:
void(A::*BF)();
};
int main()
{
A a;
B b;
b.BF = &A::AF;
(a.*b.BF)();
return 0;
}
I want to use it like the code below.
is this possible?
Or is there something else to replace the function pointer?
class A {
public:
void AF() { cout << "A::F" << endl; }
};
class B {
public:
void(* BF)();
};
int main()
{
A a;
B b;
b.BF = a.AF;
return 0;
}
I solved the question through the answer.
Thanks!
#include <functional>
#include <iostream>
class A {
public:
void AF() { std::cout << "A::F" << std::endl; }
};
class C {
public:
void CF() { std::cout << "C::F" << std::endl; }
};
class B {
public:
B(){}
std::function<void()> BF;
};
int main() {
A a;
C c;
B b;
b.BF = std::bind(&A::AF, &a);
b.BF();
b.BF = std::bind(&C::CF, &c);
b.BF();
int i;
std::cin >> i;
return 0;
}
What you want to do is probably something like this. You can use std::function to hold a pointer to a member function bound to a specific instance.
#include <functional>
#include <iostream>
class A {
public:
void AF() { std::cout << "A::F" << std::endl; }
};
class B {
public:
B(const std::function<void()>& bf) : BF(bf) {}
std::function<void()> BF;
};
int main() {
A a;
B b1(std::bind(&A::AF, &a)); // using std::bind
B b2([&a] { a.AF(); }); // using a lambda
b1.BF();
b2.BF();
return 0;
}
Here's a C# style implementation of the accepted answer, It is memory efficient and flexible as you can construct and delegate at different points of execution which a C# developer might expect to do:
#include <iostream>
#include <functional>
using namespace std;
class A {
public:
void AF() { cout << "A::F" << endl; }
void BF() { cout << "B::F" << endl; }
};
class B {
public:
std::function<void()> Delegate;
};
int main() {
A a;
B b;
b.Delegate = std::bind(&A::AF, &a);
b.Delegate();
b.Delegate = [&a] { a.BF(); };
b.Delegate();
return 0;
}
i'd like to invoke runtime-bound functions of classes, that inherit a binding ability from a common class "Bindable". Is that actually possible?
Here's a stub which surely lacks a lot of template-arguments and namespaces:
#include <iostream> // std::cout
#include <functional> // std::bind
#include <map> // std::map
class Bindable {
public:
void bindFunction (int x, auto newFn) {
mFns.insert(std::pair<int, auto>(x,newFn));
}
void invokeFunction (int key) {
mFns.at(key)();
}
protected:
std::map<int, function> mFns;
};
class A : Bindable {
void funAone (void) {
cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
cout << "called funAtwo" <<std::endl;
}
};
class B : Bindable {
void funBone (void) {
cout << "called funBone" <<std::endl;
}
void funBtwo (void) {
cout << "called funBtwo" <<std::endl;
}
};
int main() {
A a;
B b;
a.bindFunction(1, &A::funAone);
a.bindFunction(2, &A::funAtwo);
b.bindFunction(1, &B::funBone);
b.bindFunction(2, &B::funBtwo);
a.invokeFunction(1);
a.invokeFunction(2);
b.invokeFunction(1);
b.invokeFunction(2);
}
Option #1
Use a CRTP idiom to know what type of pointers to member functions can be stored:
template <typename T>
struct Bindable {
void bindFunction (int x, void(T::*newFn)()) {
mFns.insert(std::make_pair(x,newFn));
}
void invokeFunction (int key) {
(static_cast<T*>(this)->*mFns.at(key))();
}
protected:
std::map<int, void(T::*)()> mFns;
};
struct A : Bindable<A> {
void funAone (void) {
std::cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
std::cout << "called funAtwo" <<std::endl;
}
};
DEMO 1
Option #2
Use a type-erasure and make bindFunction a function template:
struct Bindable {
template <typename T, typename std::enable_if<std::is_base_of<Bindable, T>{}, int>::type = 0>
void bindFunction (int x, void(T::*newFn)()) {
mFns.insert(std::make_pair(x, std::bind(newFn, static_cast<T*>(this))));
}
void invokeFunction (int key) {
mFns.at(key)();
}
protected:
std::map<int, std::function<void()>> mFns;
};
struct A : Bindable {
void funAone (void) {
std::cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
std::cout << "called funAtwo" <<std::endl;
}
};
DEMO 2
In both cases you can use the code as follows:
int main() {
A a;
B b;
a.bindFunction(1, &A::funAone);
a.bindFunction(2, &A::funAtwo);
b.bindFunction(1, &B::funBone);
b.bindFunction(2, &B::funBtwo);
a.invokeFunction(1);
a.invokeFunction(2);
b.invokeFunction(1);
b.invokeFunction(2);
}
Output:
called funAone
called funAtwo
called funBone
called funBtwo
Yes, it's possible, using std::bind. Note that auto can't be used as a function or template argument.
#include <iostream> // std::cout
#include <functional> // std::bind
#include <map> // std::map
class Bindable {
public:
typedef std::function<void()> Function;
void bindFunction (int x, Function newFn) {
mFns.insert(std::pair<int, Function>(x,newFn));
}
void invokeFunction (int key) {
mFns.at(key)();
}
protected:
std::map<int, Function > mFns;
};
class A : public Bindable {
public:
void funAone (void) {
std::cout << "called funAone" <<std::endl;
}
void funAtwo (void) {
std::cout << "called funAtwo" <<std::endl;
}
};
class B : public Bindable {
public:
void funBone (void) {
std::cout << "called funBone" <<std::endl;
}
void funBtwo (void) {
std::cout << "called funBtwo" <<std::endl;
}
};
int main() {
A a;
B b;
a.bindFunction(1, std::bind(&A::funAone, a)); // more than one way to bind
a.bindFunction(2, std::bind(&A::funAtwo, &a)); // the object parameter
b.bindFunction(1, std::bind(&B::funBone, b));
b.bindFunction(2, std::bind(&B::funBtwo, &b));
a.invokeFunction(1);
a.invokeFunction(2);
b.invokeFunction(1);
b.invokeFunction(2);
}
Why executing this code:
// DefaultAny.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <exception>
using std::cout;
template<class T>
struct NoReturnPolicy
{
static void calculate(T& result, const T& source)
{
result = source;
}
};
template<class T>
struct ReturnPolicy
{
static T& calculate(T& result, const T& source)
{
result = source;
return result;
}
};
template<class T>
struct ThrowPolicy
{
static void check(T* ptr)
{
cout << "ThrowPolicy";
struct Nullptr: public std::exception{};
if(!ptr)
{
throw Nullptr("Nullptr not allowed");
}
}
};
template<class T>
struct NoThrowPolicy
{
static T* check(T* ptr)
{
cout << "NoThrowPolicy";
if(!ptr)
{
return nullptr;
}
else
{
return ptr;
}
}
};
/*
If pointer already points at
something no assignement is being done
*/
template<class T, class ThrowingPolicy>
struct NoAssignPolicy
{
static T* check(T* dest,const T*const src)
{
cout << "NoAssignPolicy";
if (!ThrowPolicy::check(dest))
{
dest = operator new(sizeof(T));
new (dest) T(*src);
}
}
};
template<class T,class ThrowingPolicy>
struct NoCheckPolicy
{
static void check(T* p)
{
cout << "NoCheckPolicy";
}
};
template<class T,class ThrowingPolicy>
struct CheckPolicy
{
static void check(T* p)
{
cout << "CheckPolicy";
ThrowingPolicy::check(p);
}
};
template<
class T,
class ThrowingPolicy = NoThrowPolicy<T>,
class CheckingPolicy = NoCheckPolicy<T,ThrowingPolicy>,
class AssigningPolicy = NoAssignPolicy<T,ThrowingPolicy>,
class ReturningPolicy = NoReturnPolicy<T>
>
struct BreadSlicer
{
BreadSlicer()
{
cout << "Type: " << typeid(T).name() << '\n';
cout << "ThrowingPolicy: " << ThrowingPolicy::check(0) << '\n'; //
//<<<---------The second call to cout makes output on my console:
//NoThrowPolicy:"NoSpace"ThrowingPolicy:"Space"000000
}
};
//The words NoSpace and Space do not actually appear in my console ;) and they are in the opposite order.
int _tmain(int argc, _TCHAR* argv[])
{
BreadSlicer<int> a;
return 0;
}
See comments in first struct above main.
This is the result of unspecified behavior. If you have:
cout << a() << b() << c() << endl;
The order of execution of a, b, and c is not defined (yes, their results are added to the cout stream in a predictable order, but execution of the functions is not in defined order).
If your question is why "NoThrowPolicy" gets output before "ThrowingPolicy", the answer is that there's no sequence point guaranteeing an ordering for the call to ThrowingPolicy::check(0) and the call to operator<<(cout, "ThrowingPolicy: "). C++ is allowed to call those functions in either order.