I have a problem with static members of a class not being initialized before the constructor. Am i doing something wrong? Is it a bug in G++ ?
Any workarounds?
g++ --version : (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
I am also using Eclipse as my IDE, but i just copy the static lib headers to /usr/include/StaticTestLib/InitTest.h and the library to /usr/lib/x86_64-linux-gnu/libStaticTestLib.a
Note this only happens if the object that holds the data is defined before main and the class is in a Static Library.
Static library header (the static library itself is named StaticTestLib):
InitTest.h
#include <iostream>
namespace StaticTestLib {
class notifier_header{
public:
notifier_header(){
std::cout<<"static var init"<<std::endl;
}
};
class InitTest {
public:
static notifier_header _header_notifier;
InitTest();
virtual ~InitTest();
};
}
Static library source file:
InitTest.cpp
#include "InitTest.h"
namespace StaticTestLib {
notifier_header InitTest::_header_notifier;
class notifier_cpp{
public:
notifier_cpp(){
std::cout<<"code before constructor"<<std::endl;
}
}_notifier_in_cpp;
InitTest::InitTest() {
std::cout<<"constructor"<<std::endl;
}
InitTest::~InitTest() {
std::cout<<"destructor"<<std::endl;
}
}
This program:
StaticTest.cpp
#include <iostream>
#include <StaticTestLib/InitTest.h>
StaticTestLib::InitTest test;
int main() {
std::cout << "program main" << std::endl;
std::cout << "program end" << std::endl;
return 0;
}
… outputs:
constructor
static var init
code before constructor
program main
program end
destructor
But this program:
#include <iostream>
#include <StaticTestLib/InitTest.h>
int main() {
std::cout << "program main" << std::endl;
StaticTestLib::InitTest test;
std::cout << "program end" << std::endl;
return 0;
}
… outputs:
static var init
code before constructor
program main
contructor
program end
destructor
My guess is that this is related to the order of static objects initialisation in different compilation units being undefined.
The second code snippet where you create a test object in your main is easy to explain. Static initialisation will always happen before any code is executed, so by the time you enter main, your notifier_header object is definitely created.
Now, when you create your test before main, you have two static objects. notifier_header object does not depend on your InitTest: it is scoped within that class, but it is stored in static memory. You seem to reference the notifier_header in your InitTest.cpp, which is a different compilation unit to main. A compiler is free to do static allocations in any order for those two units, provided that there is no interdependencies.
If your constructor depended on notifier_header, you could use it as a singleton. Create a function that returns an instance of a static object (headerInstance in the example below), and upon its call, the object will be created:
#include <iostream>
namespace StaticTestLib {
class notifier_header{
public:
notifier_header(){
std::cout<<"static var init"<<std::endl;
}
};
class InitTest {
public:
InitTest();
virtual ~InitTest();
notifier_header& headerInstance();
};
}
Static library source file (InitTest.cpp)
#include "InitTest.h"
namespace StaticTestLib {
class notifier_cpp{
public:
notifier_cpp(){
std::cout<<"code before constructor"<<std::endl;
}
}_notifier_in_cpp;
InitTest::InitTest() {
headerInstance();
std::cout<<"constructor"<<std::endl;
}
InitTest::~InitTest() {
std::cout<<"destructor"<<std::endl;
}
notifier_header& InitTest::headerInstance() {
static notifier_header _header_notifier; // will only be constructed once
return _header_notifier;
}
}
The output I get:
static var init
constructor
code before constructor
program main
program end
destructor
Related
I am student, and I am trying to build a project. My program is throwing an error while accessing the vector. The size of the vector is 1, but when I call RenderQueue.front it throws an error:
front() called on empty vector.
My code is below:
global.h
struct RenderStruct {
std::function<void()> testfunction1;
std::function<void()> testfunction2;
};
static std::vector<RenderStruct> RenderQueue;
Test.h
class test
{
public:
static void add_to_queue();
};
Test.cpp
void test::add_to_queue()
{
std::function<void()> testfunction1 = [&]()
{
std::cout << "First Function Working" << std::endl;
};
std::function<void()> testfunction2 = [&]()
{
std::cout << "Second Function Working" << std::endl;
};
RenderQueue.push_back({testfunction1, testfunction2});
};
Main.cpp
int main()
{
test::add_to_queue();
auto front = RenderQueue.front();
front.testfunction();
front.testfunction2();
};
static linkage variables are not shared between compilation units (cpp files).
Make your variable non static, mark it as extern, then export it from one cpp file (by declaring it without extern there).
I am using a static method to initialise the const fields of a class. The static method uses some const variables that are stored in a separate header file. Primitive types are correctly being passed to the static method, but the std::strings are being passed empty. I cannot understand why this is.
After doing some searching I have stumbled upon something called the static initialiser fiasco, but I'm having trouble wrapping my head around it, and can't work out if it is to blame. As the the object is in global scope, is the problem that it is being 'setup' before the std::string class has been 'setup'?
I have tried to replicate a minimal example below:
// File: settings.hpp
#include <string>
const std::string TERMINAL_STRING "Printing to the terminal";
const std::string FILE_STRING "Printing to a file";
// File: printer.hpp
#include <string>
#include <iostream>
class Printer
{
private:
const std::string welcomeMessage;
static std::string initWelcomeMessage(std::ostream&);
public:
Printer(std::ostream&);
}
extern Printer::print;
// File: printer.cpp
#include "settings.hpp"
std::string Printer::initWelcomeMessage(std::ostream &outStream)
{
if (&outStream == &std::cout)
{
return (TERMINAL_STRING);
}
else
{
return (FILE_STRING);
}
}
Printer::Printer(std::ostream &outStream) :
message(initWelcomeMessage(outStream)
{
outStream << welcomeMessage << std::endl;
return;
}
// File: main.cpp
#include "printer.hpp"
printer print(std::cout);
int main()
{
return (0);
}
Thanks very much!
As the the object is in global scope, is the problem that it is being 'setup' before the std::string class has been 'setup'?
Yes.
Have your strings be function-statics, returned by reference from some function, instead.
This is the traditional fix for the static initialisation order fiasco.
Not sure how correctly formulate the question but here is the problem.
I have a static lib where I have the following class in a.h:
#pragma once
#include <vector>
class A{
public:
void Run() {
data_.push_back(10);
std::cout << "size: " << data_.size() << std::endl;
}
private:
static std::vector<int> data_;
};
a.cpp is as follows:
#include "a.h"
std::vector<int> A::data_;
And I have another class in b.h:
#pragma once
#include <string>
class B
{
public:
static std::string Get();
};
And b.cpp:
#include "b.h"
#include "a.h"
std::string B::Get()
{
static A a;
a.Run();
return "foo";
}
Now my main app which is using the above static lib is as follows:
#include <iostream>
#include "a.h"
#include "b.h"
static std::string var1= B::Get();
int main(int argc, char** argv)
{
A a;
a.Run();
}
Trying to understand why the output is:
size: 1
size: 1
There should be a single instance of each static data member for the entire class, so there should be a single call to A::data_ constructor.
Am I hitting "static initialization order fiasco"? I.e. data_ is not initialised before I use it, but then I should be getting the crash?
And now lets imagine my data_ holds dynamically initialised items (something none POD). How will it be destructed if at the end data_ holds one item, although I've inserted 2?
And that's what actually is happening in my real life code (it sometimes crashes during destruction of data_).
Getting rid of global static ( static std::string var1= B::Get(); ) solves the problem, but I still want to understand the under the hood problem.
The described case can be reproduced in VS2015 (the real life case is reproducible in gcc 6.2 )
Am I hitting "static initialization order fiasco"?
Most likely.
You can remove the problem by making the static data of a class available via a function call. E.g.
class A{
public:
void Run() {
getData().push_back(10);
std::cout << "size: " << getData().size() << std::endl;
}
private:
static std::vector<int>& getData();
};
std::vector<int>& A::getData()
{
static std::vector<int> data;
return data;
}
When you do that, data will be initialized when A::getData() is called the first time. It removes the static initialization order issue completely.
I want to create a static function pointer array, so I can jump to a certain function regarding a received index. Like an index jumper.
So imagine a class like this:
Class A
{
private:
static void 1stFunction();
static void 2ndFunction();
static void(*functionPointer[20])(void);
};
Then I would like that functionPointer to get the value of the 1stFunction and 2ndFunction, and maybe even more.
So, how do I initialize it?
As far as I know, when a static member is declared, you can use it even before an instance is created. So I though, lets initialize that function pointer, so later I can call it like this
functionPointer[receivedIndex]();
So i tried to initilize it like this, in the same .h file
void (*A::functionPointer[])(void) =
{
A::1stFunction,
A::2ndFunction,
};
But the compiler gives me redifinition, it says it's already created.
So, pretty sure I'm missing something. I don't know though, if it is syntax or simply it is not possible to do it this way.
I know that function pointers to class's member functions are different than normal function pointers... But this is a static function, so I believe it doesn't belong to an instance and therefore it should work with normal function pointers.
Any help would be appreciated.
Thanks
The following would be a working example that probably achieves what you need.
You need C++11 for the initializer list.
It is a good practice to initialize the static member in the cpp file, as you don't want to have a definition of the static member everytime the header is included (this can lead to linking issues).
You can call callf with the desired index and have the corresponding function called, based on the initialization of the function pointer array.
The output of the program would be:
I am 2ndFunction
Header file
class A
{
private:
static void Function1();
static void Function2();
static void(*functionPointer[20])();
public:
static void callf(int index);
};
Implementation
#include <iostream>
#include "ex.h"
void(*A::functionPointer[20])() {
A::Function1,
A::Function2
};
void A::Function1() {
std::cout << "I am 1stFunction" << std::endl;
}
void A::Function2() {
std::cout << "I am 2ndFunction" << std::endl;
}
void A::callf(int index) {
A::functionPointer[index]();
}
int main(int argc, char const *argv[]) {
A::callf(1);
return 0;
}
Here you have a more modern C++ approach (C++14 needed)
I would advise you to explore lambda functions if you are not restricted to C++03.
#include <iostream>
#include <functional>
#include <vector>
class A {
public:
using f_type = std::function<void(void)>;
f_type f1 = []() { std::cout << "f0" << std::endl;};
f_type f2 = []() { std::cout << "f1" << std::endl;};
static void f3() { std::cout << "f3" << std::endl; }
std::vector<f_type> functions{f1, f2, f3};
};
int main() {
A a;
a.functions[0]();
a.functions[1]();
//adding custom lambda
a.functions.emplace_back([](){ std::cout << "custom f" << std::endl;});
a.functions[2]();
return 0;
}
you can add both functions and lambdas to your container.
So I've been working on my what I thought would be quick and easy project for a couple hours now and I can't get it to work! It's making me frustrated lol I've got to be close, but maybe I'm not.
I'll include my code with comments explaining what it should be doing. Essentially its using a private constructor and destructor. A member integer and then a public static function to return a reference to an object in the class - and a public function that should display the member integer and increment it. I keep getting scope and initialization errors.
HERES THE ERRORS:
Singleton.h: In function ‘int main(int, char**)’:
Singleton.h:28:2: error: ‘Singleton::Singleton()’ is private
main.cpp:38:12: error: within this context
Singleton.h:29:2: error: ‘Singleton::~Singleton()’ is private
main.cpp:38:12: error: within this context
Any help or suggestions will be greatly appreciated!
Heres my code (Singleton.h, Singleton.cpp, main.cpp):
Singleton.h :
#ifndef SINGLETON_H
#define SINGLETON_H
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
class Singleton {
public:
static Singleton& instance(); //returns a reference to a Singleton obj
void sendOutput(); //prints member variable and increments it
private:
int myInt; //member integer-variable
Singleton(); //constructor
~Singleton(); //destructor
};
#endif
Singleton.cpp :
#include <string>
#include "Singleton.h"
using namespace std;
//Displays to console that the obj was created. Initializes the member variable
Singleton::Singleton(){
myInt = 0; //member variable
cout << "Singleton Object Created!" << endl;
}
//destructor - displays to console that the Singleton object was destructed
Singleton::~Singleton(){
// delete myObj;
cout << "Singleton Object Destructed!" << endl;
}
//display member variable value and increment
void Singleton::sendOutput(){
cout << "Request to send data to output to console" << endl;
cout << "Integer Value: " << myInt << endl;
myInt++;
}
//REQUIRED: Static method with a reference to an object of this class return type
//create a static Singleton object and return it
Singleton& Singleton::instance(){
static Singleton myObj;
return myObj;
}
main.cpp :
#include "Singleton.h"
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
//Another requirement - demo static variables
void static_test(){
static int a = 1;
cout << a << endl;
a++;
}
int main(int argc, char * argv[]){
static_test();
static_test();
static_test();
//messed around with this for awhile - got it to work a few times
//messed it up a few more times O.o
Singleton mySingletonObj;
Singleton& sRef = Singleton::instance();
//sRef = Singleton::instance();
sRef.sendOutput();
return 0;
}
Thought/Suggestions/Questions/Concerns?
Anything will help relieve the frustration this has been causing me lol. It seems too simple to be causing me such a problem. Thanks!
Forbidden in that scope:
Singleton mySingletonObj;
Should be OK:
Singleton& sRef = Singleton::instance();
References are not reassignable:
sRef = Singleton::instance();
Should be OK:
sRef.sendOutput();
Also, remove this -- the language already specifies the lifetime and storage of the object, and takes care of destructing it:
delete myObj;
You should also delete the ability to copy the type:
Singleton(); //constructor
Singleton(const Singleton&) = delete; // deleted copy constructor
Just remove delete myObj; here:
Singleton::~Singleton(){
delete myObj;
cout << "Singleton Object Destructed!" << endl;
}
and it should work. myObj is statically allocated so will be deleted by runtime on process exit.
First of all you should understand basics of the language before yo start writing programs on it. From your code looks like you try to delete myObj, which is local static object from another method and not visible in destructor, not to mention that you can call delete only on pointers and should delete only pointers initialized by operator new.
Also your singleton should have private or deleted (for C++11) copy constructor and assignment operator. If you do that line: "sRef = Singleton::instance();" will not compile (and it should not logically). Other than that everything is fine.