C++ :: Constructors In A Singleton

Apr 6, 2013

I need to implement a singleton, so I've been reading about it online and I'm still not quite sure about all the types of constructors I need to declare:

Code:
class my_singleton {
private:
my_singleton();
my_singleton(my_singleton & X);
my_singleton(const my_singleton & X);

[Code] ....

Is this OK?

View 8 Replies


ADVERTISEMENT

C++ :: Getting Singleton Instance

Oct 25, 2014

Code:

class BoundingBoxTest : public DemoApplication {
public:
#ifdef DYNAMIC_CHARACTER_CONTROLLER
btCharacterControllerInterface* m_character;

[Code] ....

I am creating the object by calling : BoundingBoxTest::Create();

Do I make a getter to retrieve the demo object or do I build on the Create() method... So that it will return the instance if it is not null. and creates one if there is none?

View 3 Replies View Related

C++ :: How To Create A Singleton Class

Oct 6, 2013

I've tried to program a Singleton class. But the problem is that I don't know how to access the g_pInstance() function. Because this is not working because the constructor and deconstructor is private:

Singleton::g_pInstance()
Code: #include <iostream>
using namespace std;
class Singleton
{

[Code]....

I'm not sure of how to access any object, function, variables in the class when you are using a Singleton. How do you access that?

I'm just asking because I want to know how to do that if I have to use a Singleton sometime when I'm programming.

View 5 Replies View Related

C/C++ :: Creating A Singleton Pointer?

Jun 26, 2014

I have a class in my application that only needs to be created once, but the object needs to be available to all other classes in my application if necessary. Since declaring everything static can be restrictive (as I understand), I created a class like this:

class Foo {
// Data members
// Constructor/Destructor
// Functions
};
extern Foo* myFoo = new Foo();

And then the global variable gets deleted at the very end of the main method when everything is done:

#include "Foo.cpp" // (yes, I know this is normally bad, this is how I'm required to code)
int main() {
// do stuff
delete myFoo;
return 0;
}

These won't link, though, because I get undefined reference linking errors to myFoo wherever I use it. I'm pretty sure this means I'm creating a singleton wrong, but I'm not sure what I'm doing wrong -- there's no const conflicts and the pointer is properly initialized (to my understanding). If there's a better way to do this than extern, I'm completely open to it, as long as it's understandable and works.

View 9 Replies View Related

Visual C++ :: How To Use Watch When Using Singleton

Aug 24, 2014

I have code like this:

Code:
if (S::I().File.isDirectory(arg, S::I().Stat.workingPath)) {
// find out if there is -r option after 1st argument to join files
src_temp.join = true;
S::I().Stat.getRegEx = true;
}

The S is singleton class and I() returns instance of Singleton; there is a Stat object too. When I debug (line by line) I would like to see what values are in the Stat object. Is it possible to do it using Watch panel in Visual Studio 2010?

View 7 Replies View Related

C++ :: Singleton Destruction Order

May 28, 2012

I've been upkeeping a mess of a code recently, that uses "pseudo" singletons. Basically, the current code has "Initialize_All" static functions that initializes all the singletons in a given order. At the end of the program, we call "Destroy_All", and destroy everything in the reverse order.

The code is actually heavilly dll'ed, and Initilize_All and Destory_All are referenced counted. We ask that any client who uses our code call Initialize_All first and then Destroy_All when they are finished. The first Initilize_All will initialize everything, and the last Destory_All will delete everything.

This is showing its limits.

I'd like to move us to a fully singleton design. The singleton pattern means we don't have to use an Initilize_All, and each singleton can manage construction dependencies by itself (we are mono-threaded).

Each singleton is "clean", so it is cleans itself up at dll destruction.

The big question is this one:

If there is a singleton dependency during destruction, eg: ~A requires an instance of singleton B (which is in another DLL), are we guaranteed proper behavior?

Or, is there an "Static de-initialization order fiasco"?

If yes, are there any design that can combat this fiasco, short of having each singleton register itself in a manager, that will destroy them in reverse order?

View 6 Replies View Related

C++ :: Singleton Class For User Settings?

Oct 11, 2014

My current idea of how to work with user settings goes like this:

1. Create a class to hold all of the user settings.
2. Use that class to load/save/hold settings in memory.
3. Create an instance of that class once in the entry point of the program (int Main or whatever).
4. Pass, by reference this same class instance around to all of the other classes that need the user settings.
5. Once all other objects deleted, save and then delete the User Settings class.

I created a psuedo-code example below of this. My question is if this is the best way or should I be doing something else. In particular, I am wondering if somehow I can avoid passing the settings class by reference all of the time. Would this be a good case scenario for a "Singleton" type class?

#include <string>
class UserSettings {
private:
std::string SettingOne;
int SettingTwo;
bool SettingThree:

[Code] ....

View 9 Replies View Related

C++ :: Out Of Bounds Access (Array / Singleton)

Feb 3, 2014

#include <iostream>
int main() {
int bit = 1;
int init = 0xf ^ (1 << bit);
char* c = new char(2);
sprintf(c, "%x", init);
std::string initVal = std::string("4'h") + c;
std::cout << initVal << std::endl;
}

Above code is compiling as I expect it to be.

Problem is when I run it, it prompts me the following message:

Out-of-bounds access (ARRAY_VS_SINGLETON). Passing "c" to function "operator +(HSTString const &, char const *)" which uses it as an array. This might corrupt or misinterpret adjacent memory locations.

View 2 Replies View Related

C++ :: Singleton Pattern - Delete Pointer Twice

Feb 22, 2012

environment : qt creator 4.7

code:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class singleTon {

[Code] ....

this is a singleton pattern first,it doesn't matter, why I could delete this pointer twice?because the gcc compiler?That mean in the surface, "delete pInstance1;" this movement just mark the memory pInstance1 has been deleted but not real?does any one encounter this phenomenon?

View 7 Replies View Related

C++ :: Tag Dispatching Constructors

Dec 24, 2014

#include <iostream>
#include <string>

struct A {
struct Tag{};
std::string name;
int value;
A (const std::string& n, int v) : name(n), value(v) {}
A (const std::string& n, int v, Tag) : name(n), value(v) {std::cout << "Constructor with Tag called.

[Code] ....

How to avoid having to type out a second near-identical constructor for any class like D and E which have specialized constructors different from A? You can imagine the nuissance this causes if there are many classes like D and E (and with many parameters) that need the Tag parameter. The nuisance will be there to when making changes to the constructors. Delegated constructors I don't think will work because of passing `tag` into the parent's constructor. Is there some sort of inheritance trick I can apply simultaneously to all such classes to get them all to behave like B and C's constructors?

View 2 Replies View Related

C/C++ :: Declaring Map Global Or Wrap In Singleton Class

Jul 13, 2014

#include <map>
#include <iostream>
#include <stdexcept>

[Code]....

SuperSmartPointer<int> ptr4((int*)ch); this line gives error error as double deletion will occur.

Solution :
1) make the reference map global variable.
2) wrap the map in a non-template singleton class.

View 1 Replies View Related

C++ :: Multiple Default Constructors Specified

Dec 16, 2014

I have an inherited class that essentially manages a Qt Window.

It is as follows (prototype below):

class QTMyOpenGLWindow : public QWindow, protected QOpenGLFunctions {
Q_OBJECT

[Code] ....

Now, I can understand the confusion of the compiler, but the functionality as I laid it out works for me (I can create the class with just specifying the parent and also have the option of preventing auto-initialization when creating). But, is there a better approach?

View 3 Replies View Related

C++ :: Constructors In Derived Classes

Apr 7, 2014

As long as no base class constructor takes any arguments, the derived class need not have any constructor, if one or more arguments are used then it is mandatory for the derived class to have a constructor and pass the arguments to base class constructors. While applying inheritance, we usually create objects using derived class. Then it makes sense for the derived class to pass arguments to the base class constructor. When both the base and derived class contain constructors ,the base class constructor is execute first.

In case of multiple inheritance, the base classes are constructed ,in the order in which they appear in the declaration of the derived class. Similarly in a multiple inheritance the constructors will be executed in order of inheritance. Since the derived class takes the responsibility to supply initial values to the base class,we supply the initial values that are required by all the classes together where the derived class object is declared.

The constructor of the derived class receives the entire list of values of arguments and pass them on to the base constructors int the order in which they are declared in the derived class

View 1 Replies View Related

C++ :: Copy Constructors In Inheritance

May 16, 2013

#include <iostream>
using std::cout;
using std::endl;
class CBox // Base class definition
{
public:
// Base class constructor
explicit CBox(double lv = 1.0, double wv = 1.0, double hv = 1.0) : m_Length(lv), m_Width(wv), m_Height(hv)

[Code] .....

This example produces the following output:

// Derived class copy constructor
CCandyBox(const CCandyBox& initCB): CBox(initCB) {
std::cout << std::endl << "CCandyBox copy constructor called";
// Get new memory
m_Contents = new char[ strlen(initCB.m_Contents) + 1 ];
// Copy string
strcpy_s(m_Contents, strlen(initCB.m_Contents) + 1, initCB.m_Contents);
}

It will work right? Cause when I do "CBox(initCB)" it only sends the BASE part of the derived object to the base class copy constructor, is it copy or default?

View 6 Replies View Related

C++ :: Using Constructors In Template Class?

Sep 13, 2014

The code below references to a header file and implementation .cpp file, which are not important. My question is what is the proper way to use a constructor in a main file. I have been getting "invalid use of" errors when using letters.Pair(a,b), where Pair(T a, T b) is a constructor that accepts arbitrary type T of variables 'a' and 'b'. So I played around a bit and suddenly found a syntax that works. I need verification for the syntax below:

#include <iostream>
#include "pair.h"
#include "pair.cpp"

[Code].....

Are the comments with the asterisks correct? As in this is always the way you initialize and assign? So letters.Pair(a, b) is not the right way to use constructors?

View 2 Replies View Related

C/C++ :: Calling Constructors With Parameters

May 28, 2014

I created 3 Rectangle pointers. And later in the program, I would like to modify these existing Rectangles by calling constructors with parameters. Is this possible? I have a sense that it involves creating overload operators, but I am not sure how to do it, or if that's the correct path.

#include <iostream>
#include <string>
using namespace std;
// Base class
class Shape {
protected:
int width;
int height;

[code]....

View 6 Replies View Related

C++ :: Link Error Although All Constructors Appear To Be There

Feb 16, 2015

I'm getting a massive 1300 char link error with VC10. It appears to complain that it can't see the constructor although the constructor is definitely there.

Error:
test_GatewayNS.obj : error LNK2019: unresolved external symbol "public: void __thiscall std::allocator<class BinarySearchVector::ElementTemplate<class Gateway,unsigned __int64> *>::construct(class BinarySearchVector::ElementTemplate<class Gateway,unsigned __int64> * *,class BinarySearchVector::ElementTemplate<class Gateway,unsigned __int64> * const &)"

[Code] ....

However, the constructors seem to be there and if I copy them into my program just to make sure - the compiler complains that they are already defined:

namespace BinarySearchVector {
template <class ElementType, class IdType> class ElementTemplate //allows comparison functions to be redefined {
public:
ElementTemplate(IdType myId) : id(myId), tickCount(0), requestingDeletion(false) {};

[Code] ....

Any clues as to what I'm missing ?

View 2 Replies View Related

C++ :: Singleton Base Class - How To Implement GetInstance Function

Aug 20, 2014

I'm playing with the idea of a singleton base class, but I'm having an issue with how to implement the GetInstance() function in the base class. Since I'm trying to make this ridiculously simple for the child, I'd like to handle that in the base.

class Singleton {
private:
static Singleton* instance;
Singleton() { Construct(); } // Private to avoid other instances

[Code] .....

It would be easy to use like so:

class Hello : public Singleton {
private:
std::string hello;
void Construct() { hello = "hello"; }
public:
std::string GetHello() const { return hello; }
};

Then the instance would be handled like so:
std::cout << Hello::GetInstance()->GetHello();

View 12 Replies View Related

C++ :: Singleton Class - Auto Seems To Return Wrong Type

Jul 18, 2013

I am trying out a technique for a singleton class:

// access controlled singleton, accessed through function "instance()"
// singleton is constructed in this function
// so that constructor and destructor will be used
class single {
// private constructor/destructor

[Code] .....

Playing around with the code in main(), I am having trouble with auto:

single& s = single::instance(); // works fine
auto a = single::instance(); // error ~single() is private

When I make the destructor public, the output of the program is:

ctor
dtor
dtor

So I fixed this by typing auto&. I'm still confused though, why wouldn't auto know I am returning a reference?

View 2 Replies View Related

C++ :: Singleton Design Pattern - Not All Control Paths Return A Value

Jan 17, 2013

I have the following code where I use the singleton design pattern, but I get the warning:

warning C4715: 'CM::Instance' : not all control paths return a value

Code:
CM& CM::Instance() {
DWORD dwWaitResult = WaitForSingleObject(mutex, INFINITE);
switch(dwWaitResult) {
case WAIT_OBJECT_0:

[Code] ....

How can I fix this warning?

View 4 Replies View Related

C++ :: Copy Constructors For A Dynamic Array

Dec 13, 2013

I am trying to figure out copy constructors for a dynamic array and I am definitely missing something. If I go into the copy constructor routine during debug, the values appear to be correct but they don't percolate up to the newly created object. I'll post a portion of the code below:

Code:

// include header files for the classes that are being used
#include "stdafx.h" //

NOTE: THis reference must be added to all cpp files in Visual Studio Express 2013

#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
using namespace std;
const int ARRAY_SIZE_DEFAULT = 32;
class vectorOfInt {
public:

[code]....

The size of c is 0. Values of a were not copied to c, although they appear to do so within the copy constructor routine.

View 7 Replies View Related

C++ :: Default Constructors And Header Files?

Jun 8, 2013

I'm working on trying to figure out constructors and header files. Can ya'll help me out with this? I'm sure my code looks like a mess as I tried to piece together different solutions I've found. There's also an attempted copy constructor and operator function. Basically my problem is my source file says there is no default constructor for my class type. Here's my header code:

#include <iostream>
#ifndef _car
#define _car

[Code].....

View 8 Replies View Related

C++ :: Singleton Design Pattern - Why Copy Constructor Not Made As Private

Jul 9, 2014

I was going through Singleton design pattern and get to know that objects can be created only by static function of that class and constructors are make private.

My question is, why assignment operators are not made private through which we can create a copy of already existing object.

I tried below code and assignment works, so I have new object sc3. I know that its referring to memory of sc1 but finally I was able to create object without using static function.

Also, why copy constructor not made as private.

Below is code:

#include <iostream>
using namespace std;
class Singleton {
private:
static bool instanceFlag;

[Code] .....

View 3 Replies View Related

C++ :: Writing Test Programs Involving Constructors

Jan 30, 2014

I am currently trying to write a test program involving constructors. I know what I am about to ask is pretty basic stuff but Visual Studio is not recognizing when I declare strings for some reason. My code isn't completed yet but as I am typing string in to declare the variable in the class Visual Studio is not recognizing string as a usable value.

Code below:

#include <cassert>
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;
class college {

[Code] .....

Like I said... this is completely unfinished I just need to understand why my strings aren't being recognized.

View 2 Replies View Related

C++ :: Class Constructors And Data Member Initialization

Oct 29, 2014

I recently discovered the new - new to me anyway! - feature of modern C++ that allows you to set the initial value of a data member when you declare it:

class CINTWrapper{
private:
int m_iData=0;
};

This even extends to calling member functions that work with initialization I believe:

class CStringWrapper{
private:
wchar_t* Allocate_Array(const int iBufferSize);
wchar_t* m_pString=Allocate_Array(1);
};

At first, this seemed an extremely useful piece of functionality that C++ had been lacking all along. However, the more I thought about it the more it struck me this feature actually undermines one of the principle design elements of the language - that being the Constructor.

As I understand it the primary purpose of the Constructor is specifically to give the programmer a place where it is guaranteed he can always initialize his data members before anything else is done with the class. However, given the new initialization rules this is no longer necessary. So it largely seems to me that Constructors as a whole are no longer necessary either! Copy-Constructors are a special and vital case. Admittedly when I was using them for their intended purpose I hated either the redundancy you had to introduce across multiple Constructors; those with and without arguments and so on, or alternately the fine tuning of helper-functions to do common initialization between these variants. Now however I sort of regret this cast-iron rule has been taken away.

As a last point, I am trying to change the way I think about programming. I am trying to employ more objects than pure C-style ('int' or 'double', etc) data types and especially to move into templates (although absolutely NOT the Hewlett Packard template library!). Given my current understanding of inheritance in particular it seems to me that using pre-initialized data members rather than Constructor-initialization makes object derivation even more complicated, not less so.

View 16 Replies View Related

C++ :: Multiple Constructors Calling Parent Constructor

Dec 6, 2013

I have a class that extends another class, and I want multiple constructors in the child class, but the child constructor needs to call the parent constructor. This is what I have

In the child class:

ChildClass::ChildClass() {
ChildClass(1);
}
ChildClass::ChildClass(int i)
: ParentClass(i) {
// do stuff
}

In the parent class:

ParentClass::ParentClass(int i) {
// do stuff
}

In my main program:

ChildClass child1;
// do stuff with child1
// breaks
ChildClass child2(1);
// do stuff with child2
// works fine

Using the default constructor breaks my program at runtime, but using the one with a parameter works fine. The default constructor calls the other with the same thing as the main part in the program, so I would think this should make no difference, but obviously that isn't the case.

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved