Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 days ago.
Improve this question
I have 2 types of singletons; what are the differences? How come I can initialize the static member in Singletone2 class and it stays unique single on all the singleton life cycle ?
What is better? What is more thread safe?
class SingleTone2
{
public:
SingleTone2(SingleTone2& other) = delete;
SingleTone2& operator=(const SingleTone2&) = delete;
SingleTone2& operator=(SingleTone2&&) = delete;
SingleTone2* operator=(const SingleTone2*) = delete;
static SingleTone2& instance()
{
static SingleTone2 INSTANCE; // how can he be alive and unique ?
return INSTANCE;
}
int get()
{
return 1;
}
private:
SingleTone2(){}
};
class SingleTone
{
public:
SingleTone(SingleTone& other) = delete;
SingleTone& operator=(const SingleTone&) = delete;
SingleTone& operator=(SingleTone&&) = delete;
SingleTone* operator=(const SingleTone*) = delete;
static SingleTone* instance()
{
if (singletone == nullptr)
{
singletone = new SingleTone();
}
return singletone;
}
int get1()
{
return 1;
}
private:
SingleTone() {};
static SingleTone* singletone;
};
SingleTone* SingleTone::singletone = nullptr;
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I tried to override the - operator but I get an error. How to solve the error, and what is it for?
#pragma once
class Resurse
{
protected:
unsigned int _cantitate;
public:
Resurse() {}
Resurse(unsigned int cantitate) :_cantitate(cantitate) {}
~Resurse() {}
Resurse(Resurse&& r)
{
_cantitate = r._cantitate;
r._cantitate = 0;
}
virtual Resurse* operator-(Resurse* r)
{
Resurse* result=new Resurse(this->_cantitate - r->_cantitate);
return result;
}
unsigned int GetCantitate() { return _cantitate; }
};
#pragma once
#include "Resurse.h"
class Hrana:public Resurse
{
public:
Hrana() {}
Hrana(unsigned int cantitate) :Resurse(cantitate) {}
~Hrana() {}
Hrana(Hrana&& h) { _cantitate = h._cantitate; h._cantitate = 0; }
Resurse* operator-(Resurse* r)
{
Resurse* result = new Hrana(this->_cantitate - r->GetCantitate());
return result;
}
};
void main()
{
Resurse* hrana1 = new Hrana(20);
Resurse* hrana2 = new Hrana(17);
Resurse* result = hrana1 - hrana2;
system("pause");
}
Yes, it is possible to overload (not override) operators. However, the problem is, you are not doing it correctly.
You are trying to invoke operator- on Resurce* pointers, not on Resurce objects. Your operator- needs to take a Resurce object by value/reference as input, not by pointer. And return a new Resurce object by value on output, not by pointer. See What are the basic rules and idioms for operator overloading?
And in your main(), you need to dereference the pointers before calling operator-.
Try this:
Resurse operator-(const Resurse &r) const
{
return Resurse(_cantitate - r._cantitate);
}
int main()
{
Resurse* hrana1 = new Resurse(20);
Resurse* hrana2 = new Resurse(17);
Resurse result = *hrana1 - *hrana2;
std::system("pause");
delete hrana2;
delete hrana1;
}
Or, simply get rid of the pointers altogether, you don't really need them:
int main()
{
Resurse hrana1(20);
Resurse hrana2(17);
Resurse result = hrana1 - hrana2;
std::system("pause");
}
UPDATE: I just realized that you are trying to implement a polymorphic operator-. That is not going to work, mainly due to object slicing on the return value, but also because you can't overload operators for pointers.
I would suggest using a separate virtual method instead of operator-, eg:
#pragma once
#include <memory>
class Resurse
{
protected:
unsigned int _cantitate;
public:
Resurse(unsigned int cantitate = 0) : _cantitate(cantitate) {}
virtual ~Resurse() {}
Resurse(const Resurse&) = default;
Resurse(Resurse&& r)
{
_cantitate = r._cantitate;
r._cantitate = 0;
}
virtual std::unique_ptr<Resurse> subtract(const Resurse &r) const
{
return std::make_unique<Resurse>(_cantitate - r.GetCantitate());
}
unsigned int GetCantitate() const { return _cantitate; }
};
#pragma once
#include "Resurse.h"
#include <memory>
#include <cstdlib>
class Hrana : public Resurse
{
public:
Hrana(unsigned int cantitate = 0) : Resurse(cantitate) {}
Hrana(const Hrana& h) = default;
Hrana(Hrana&& h) : Resurse(std::move(h)) {}
std::unique_ptr<Resurse> subtract(const Resurse &r) const override
{
return std::make_unique<Hrana>(_cantitate - r.GetCantitate());
}
};
void main()
{
std::unique_ptr<Resurse> hrana1 = std::make_unique<Hrana>(20);
std::unique_ptr<Resurse> hrana2 = std::make_unique<Hrana>(17);
auto result = hrana1->subtract(*hrana2);
std::system("pause");
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have declared a function bool Network::areFriends(User & usr1, User & usr2) which when called unfortunately I am met with
identifier "function_name" is undefined
And the classes in which I am referring to.
Wall.h
#pragma once
class Wall
{
private:
std::list<Message> msgs_posted;
User* w_owner;
public:
Wall() = delete;
Wall(User* wownr);
virtual ~Wall();
void postMsg(User& usr ,Message msg);
void toString();
std::list<Message> getMsgsPosted();
};
Wall.cpp
#include "pch.h"
#include <iostream>
Wall::Wall(User * wownr)
:w_owner(wownr)
{
}
Wall::~Wall()
{
}
void Wall::postMsg(User& usr, Message msg)
{
//if are friends
if ((usr == *this->w_owner) || areFriends(usr,*this->w_owner)){
msgs_posted.push_back(msg);
/* does it get copied altogether? */
}
else
std::cout << "You can not post at this person's wall." << std::endl;
}
void Wall::toString()
{
std::list<Message> ::iterator tmp_it;
for (tmp_it = msgs_posted.begin(); tmp_it!= msgs_posted.end(); tmp_it++) {
tmp_it->toString();
}
std::cout << std::endl;
}
std::list<Message> Wall::getMsgsPosted()
{
return msgs_posted;
}
Network.h
#pragma once
class Network
{
private:
/* Singleton Implementation */
static Network* instance;
Network();
/* Misc */
std::list<User> users;
std::list<User>::iterator usr_it;
std::map<User, std::list<User*> > connections; // maybe pointer to users list?
std::map<User, std::list<User*> >::iterator map_it;
public:
/* Singleton Implementation */
Network(const Network&) = delete;
Network& operator=(const Network&) = delete;
~Network();
static Network& getInstance();
/* Other methods */
bool u_Exists(User& usr);
void addUser();
void addUser(User& usr);
void deleteUser(User& usr);
void connectUsers(User& usr1, User& usr2);
std::list<User> hasFriends(User& usr);
bool areFriends(User& usr1, User& usr2);
std::list<User> commonFriends(User* usr1, User* usr2);
};
Network.cpp
#include "pch.h"
#include <iostream>
Network::Network()
{}
...
Network& Network::getInstance()
{
static Network instance;
return instance;
}
bool Network::areFriends(User & usr1, User & usr2)
{
if (usr1 == usr2) {
return false;
}
else /*to be added*/{
return false;
}
}
The function that I am referring to is bool Network::areFriends(User & usr1, User & usr2) , used in
void Wall::postMsg(User& usr, Message msg)
{
//if are friends
if ((usr == *this->w_owner) || areFriends(usr,*this->w_owner)){
If needed I will post the rest of the classes but didn't due to size.
So shouldn't it be something like this
if ((usr == *this->w_owner) || Network::getInstance().areFriends(usr,*this->w_owner)){
In the code you've posted there's no instance of Network to call the areFriends function on.
This question already has answers here:
`auto` specifier type deduction for references
(2 answers)
Closed 5 years ago.
#include<iostream>
#include<mutex>
#include<stdlib.h>
using namespace std;
template<typename T>
class Singleton {
public:
static T& getInstance() {
if (instance_ == nullptr){
std::lock_guard<mutex> guard(mutex_);
if (instance_ == nullptr) {
instance_ = new T();
atexit(&Singleton::destroy);
}
}
return *instance_;
}
private:
static void destroy() {
delete instance_;
instance_ = nullptr;
}
Singleton() {}
Singleton(const Singleton&) {}
Singleton& operator=(const Singleton&) {}
static T* instance_;
static mutex mutex_;
};
template<typename T>
T* Singleton<T>::instance_ = nullptr;
template<typename T>
mutex Singleton<T>::mutex_;
class Test {
public:
Test() {
i_ = 0;
cout << "Construct Test" << endl;
}
void setValue(int&& x) {
i_ = x;
}
int getValue() {
return i_;
}
private:
int i_;
};
void main(){
auto instance1 = Singleton<Test>::getInstance();
auto instance2 = Singleton<Test>::getInstance();
instance1.setValue(2);
cout << instance2.getValue() << endl;
cout << instance1.getValue() << endl;
system("pause");
}
Why the type of instance1 and instance2 is Test not Test& ? "Construct Test" print only once, but the result is 0 and 2, instancen1 and instance2 seems two different Test object, the Environment is vs2015
Why the type of instance1 and instance2 is Test not Test& ?
Because you would need to use auto& in place of auto
auto& instance1 = Singleton<Test>::getInstance();
auto& instance2 = Singleton<Test>::getInstance();
You could verify that you're copying instead of getting a reference to the singleton variable with a copy constructor
Test(const Test&) {
cout << "Copying";
}
The rule is
int i = 5;
auto a1 = i; // value
auto & a2 = i; // reference
I'd also pay attention to Baum mit Augen's comment and avoid using void main and stdlib.h in the first place.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hi I'm tring to create something like wrapper class for primitive types but I'm stuck on this issue:
When I try to create interface and be able to use polymorphism with descendants
edit
I'm getting
function returning abstract class "Var" is not allowed:
function "Var::operator+" is a pure virtual
function function "Var::operator-" is a pure virtual function
function "Var::operator*" is a pure virtual function
function "Var::operator/" is a pure virtual function
Here is my code
class Var
{
public:
Var() { }
virtual Var operator+(Var b) = 0;
virtual Var operator-(Var b) = 0;
virtual Var operator*(Var b) = 0;
virtual Var operator/(Var b) = 0;
};
class Decimal : public Var
{
public:
Decimal(double a) { value = a; }
Decimal() : Decimal(0) { };
virtual Decimal operator+( Decimal b)
{
return value + b.value;
}
virtual Decimal operator-( Decimal b)
{
return value - b.value;
}
virtual Decimal operator*( Decimal b)
{
return value * b.value;
}
virtual Decimal operator/( Decimal b)
{
return value / b.value;
}
Decimal operator=(double val)
{
value = val;
}
private:
double value;
};
any solution to my problem?
I think you are going about this the wrong way. Try a template
template<class T>
class Var
{
public:
typedef T Type;
Var(const Type& value = Type()) : value(value) {}
friend Var operator+(const Var& left, const Var& right)
{
return Var(left.value + right.value);
}
private:
Type value;
};
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i write a handle class using C++. But when i run my code, i met an error.
#pragma once
#include <iostream>
using std::cout;
using std::endl;
class BaseItem{
public:
virtual BaseItem* clone()
{
return new BaseItem(*this);
}
virtual void sayHello()
{
cout<<"Hello, I am class BaseItem!"<<endl;
}
};
class ChildItem:public BaseItem{
public:
ChildItem* clone()
{
return new ChildItem(*this);
}
void sayHello(){
cout<<"Hello, I am class ChildItem!"<<endl;
}
};
template <typename T>
class Handle
{
public:
Handle():baseItem(NULL), refCount(new size_t(0)) {}
Handle(T& object):baseItem(object.clone()), refCount(new size_t(1)) {}
Handle(const Handle<T>& other):baseItem(other.baseItem), refCount(new size_t(1)) {}
Handle& operator= (const Handle<T>& other)
{
++*other.refCount;
dec_count();
baseItem = other.baseItem;
refCount = other.refCount;
return *this;
}
const T* operator->() const {return baseItem;};
const T& operator*() const {return *baseItem;};
T* operator->() {return baseItem;};
T& operator*() {return *baseItem;};
virtual ~Handle(void)
{
dec_count();
}
private:
T *baseItem;
std::size_t* refCount;
void dec_count()
{
if (-- *refCount == 0 && baseItem != NULL)
{
delete baseItem;
delete refCount;
}
}
};
This is the main function :
int _tmain(int argc, _TCHAR* argv[])
{
BaseItem item1;
ChildItem item2;
vector<Handle<BaseItem> > vec;
vec.push_back(Handle<BaseItem>(item1));
vec.push_back(Handle<BaseItem>(item2));
//for (vector<Handle<BaseItem> >::iterator iter = vec.begin();
// iter != vec.end(); iter++)
//{
//
//}
return 0;
}
when i run the code, the code crashed. i have no idea to debug the code.
This is the error:
Your Handle's copy c-tor is invalid. It should be like this:
Handle(const Handle<T>& other)
: baseItem(other.baseItem),
refCount(other.refCount)
{
++*refCount;
}
http://ideone.com/DB7L9p
The problems I can see are:
The copy constructor should share and increase the reference count, rather than create a new one;
The base class needs a virtual destructor.
The first issue causes a double deletion after copying the handle into the vector. Both copies think they are the only reference to the object and hence both try to delete it. This is probably the cause of the crash.
After fixing those, your code appears to run correctly. If you still have problems, I suggest stepping through your failing test case with a debugger.
Reference count should be a part of actual object rather than part of Handle. Handle should only increment & decrement the reference count & it should create once.
template <typename T>
class RefCounted
{
public:
std::size_t refCount;
};
class BaseItem : public RefCounted<BaseItem> {
So all classes which is being usable with Handle shall be derived from RefCounted.
template <typename T> class Handle
{
public:
Handle():baseItem(NULL) {}
Handle(T& object):baseItem(object.clone())) {++ other.refCount;}
Handle(const Handle<T>& other):baseItem(other.baseItem) { ++ other.refCount; }
Handle& operator= (const Handle<T>& other)
{
++ other.refCount;
baseItem = other.baseItem;
return *this;
}
const T* operator->() const {return baseItem;};
const T& operator*() const {return *baseItem;};
T* operator->() {return baseItem;};
T& operator*() {return *baseItem;};
virtual ~Handle(void)
{
if (baseItem != NULL && -- (baseItem->refCount) == 0)
{
delete baseItem;
}
}
private:
T *baseItem;
};
(Disclaimer: It is not a working code, just attempted to explain the concept)
If you are looking for better implementation, Refer http://trac.webkit.org/browser/trunk/Source/WTF/wtf/RefCounted.h