Error: can't allocate region after creating an object - c++

I'm learning various details of OOP in C++ and wrote that code. The purpose of that code is to toy with ctor-initializers and learn how to inirialize a reference that is a class attribute.
#include <string>
#include <iostream>
using namespace std;
class Corgi {
private:
const string nickname;
const string& rNickname;
public:
Corgi(const string& _nickname): nickname(nickname), rNickname(nickname) {}
};
int main() {
Corgi buddy("buddy");
return 0;
}
This code compiles, however, I get this error message when it runs:
Project(1343,0x7fff7b2f2000) malloc: *** mach_vm_map(size=140734714511360) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
I don't understand why I get this error message and how I can fix that. So, why do I get it and how to fix that?
I appreciate any help.

Corgi(const string& _nickname): nickname(nickname), rNickname(nickname) {}
initializes member nickname with itself which is a problem as member nickname is at this point uninitialized.
A fix:
Corgi(const string& _nickname): nickname(_nickname), rNickname(nickname) {}
Live Demo on coliru
I considered also this:
Corgi(const string& nickname): nickname(nickname), rNickname(nickname) {}
which will work for proper initialization of Corgi::nickname (due to the scope rules) but it introduces a new issue for Corgi::rNickname (which is now initialized with a reference to the constructor argument).
For this case, correct would be:
Corgi(const string& nickname): nickname(nickname), rNickname(this->nickname) {}
Live Demo on coliru

Related

How do I run a member function on a thread? [duplicate]

This question already has answers here:
Start thread with member function
(5 answers)
Closed 3 years ago.
When I compile the code below I get the following error. help me...!
Errors:
Error C2276 '&': illegal operation on bound member function expression
Error C3867 'CCore::Run': non - standard syntax; use '&' to create a pointer to member
I'm not sure if the program gives me an error.
I want to run the "Run" function of the Core class.
Core.cpp file contains only the functions created by the compiler.
I'm learning English so I'm not good yet. So please understand that the whole code.
// main.cpp
#include "Core.h"
#include <thread>
int main()
{
// The conditions below have been success
if (CCore::GetInstance().Init())
{
// The code below fails to compile.
// Error C3867 'CCore::Run': non - standard syntax; use '&' to create a pointer to member
thread main_thread(CCore::GetInstance().Run);
// Error C2276 '&': illegal operation on bound member function expression
thread main_thread(&CCore::GetInstance().Run);
main_thread.join();
}
return 0;
}
// Core.h
#pragma once
#include "Singleton.h"
#include <iostream>
using namespace std;
class CCore : public Singleton<CCore>
{
public:
CCore();
~CCore();
bool Init();
void Run();
};
// Singleton.h
#pragma once
template<typename T>
class Singleton
{
protected:
Singleton()=default;
~Singleton()=default;
public:
static T& GetInstance()
{
static T instance;
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton) = delete;
};
The compiler tells you the problem: Run() isn't a free function. It's a method, i.e. a function bound to an instance of an object. You have several options, but generally you either let the compiler synthesize a runnable for you, or write a free function yourself:
Let the compiler do all the work: guess what, it can make singletons for you so how cool is that?!
std::thread main_thread([]{
static CCore myCore;
myCore.Run();
});
You want to access that core? Sure!
std::future<CCore*> coreWhenDone = std::async([]{
static CCore myCore;
myCore.Run();
return &myCore;
});
Better yet, the core would provide some result, so that instead of accessing it directly when it's done, you could get its result (e.g. an int or std::vector<double> or whatever that core is computing)/
Let the compiler do some of the work:
std::thread main_thread([]{ CCore::GetInstance().Run(); });
Split the work between yourself and the compiler:
std::thread main_thread(std::bind(&CCore::Run, &CCore::GetInstance()));
Do all the work yourself:
void runCoreRun() {
CCore::GetInstance().Run();
}
...
std::thread main_thread(&runCoreRun);

Resolve std::string to something else than ::std::string - is it possible?

This is a follow-up question from: constructing string from NULL?
The following:
void test(const std::string& s);
int main(){
test(NULL);
}
Fails when run, but is legal c++.
In order to try to catch some of those cases, as an alternative ive considering if std::string can be replaced in the following way:
#include <string>
namespace {
namespace std {
struct string : public ::std::string { //so far everything is good
};
}
}
int main ()
{
std::string hello;//failure: ambiguous symbol
return 0;
}
Gives the following error:
<source>(17): error C2872: 'std': ambiguous symbol
C:/data/msvc/14.22.27905/include\string(19): note: could be 'std'
<source>(7): note: or '`anonymous-namespace'::std'
<source>(17): error C2872: 'std': ambiguous symbol
C:/data/msvc/14.22.27905/include\string(19): note: could be 'std'
<source>(7): note: or '`anonymous-namespace'::std'
Compiler returned: 2
I guess it is not possible to make it resolve without writing a more (fully) qualified name ? but is it possible to write std::string in the global namespace and have it resolve to something else while ::std::string is a valid type.
Background: after some failed attempts with cppcheck and cpp core check im trying to find all cases of std::string str = 0 or NULL or nullptr - since those will fail at runtime. And I thought this might be a way forward.
I ended up modifying the basic_string template ala. basic_string(int) = delete;
basic_string(::std::nullptr_t) = delete; - this won't catch all cases but does indeed seem to catch the direct cases at least
Resolve std::string to something else than ::std::string - is it possible?
[...]
...as an alternative ive considering if std::string can be replaced in the following way...
As far as I know, it is not possible outside of your anonymous namespace scope because you have no way to resolve the ambiguity (not to my knowledge).
As you can see below, since you are inside the scope of the anonymous namespace, it will be fine:
#include <string>
namespace
{
namespace std
{
struct string : public ::std::string
{
};
}
std::string hello; // Fine
}
int main()
{
std::string hello2; // Cannot be something else that ambiguous
return 0;
}
But even worse, the problem is not about std::string itself but about the std namespace.
Indeed, outside of the scope of your anonymous namespace, every call of std becomes ambiguous too.This is the error pointed by the compiler. There are two std namespaces accessible as is from the global scope.
So the following example becomes broken:
#include <string>
#include <vector>
namespace
{
namespace std
{
struct string : public ::std::string
{
};
}
std::string hello; // Fine
}
int main()
{
std::vector<int> a; // FAIL: reference to 'std' is ambiguous
return 0;
}
To fix this ambiguity over accessing the original std namespace, you'll need to write it as follows:
::std::vector<int> a; // Fully qualified name: Only way to refer to the `::std` namespace
As you can see, it still does not solve the issue and even worse, it adds a huge inconvenience.
Therefore the morality is:
Do not hide an already existing type but create a distinct one instead.
In the same way, do not hide a namespace (by defining the same namespace into an anonymous one --> evil).
(I'm open to any improvement proposal of this answer)
Could you use this kind of solution : Rather than working on std::string, you work on the function that will cause the problem
#include <string>
void test(const std::string& s){
}
// add a new function which use a pointer :
void test (const char* _Nonnull s) {
test(std::string(s));
}
int main()
{
test(NULL);
return 0;
}
Then clang will generate a warning :
1 warning generated.
ASM generation compiler returned: 0
<source>:13:14: warning: null passed to a callee that requires a non-null argument [-Wnonnull]
test(NULL);
see https://godbolt.org/z/PujFor

Error: no instance of overloaded function, in constructor (C++)

I have a very weird problem... First of all, here are my class's files:
Show.h:
#ifndef SHOW
#define SHOW
#include <iostream>
#include <string>
#include <string.h>
class Show
{
private:
std::string m_time;
int m_serial
public:
Show(const std::string &time, const int &serial);
~Show();
};
#endif
Show.c:
#include "Show.h"
Show::Show(const std::string &time,const int &serial)
{
}
As you can probably see, I only wrote the declaration of the constructor, when the visual studio underlined the second "Show" word in the Show.c file, and told me:
"void Show::Show(const std::string &time,const int &serial)
Show::Show()
Show::Show(const Show &)
Error: no instance of overloaded function "Show::Show" matches the specific type"
And when I stand with the mouse cursor over the constructor function in the Show.h file it looks like that function doesn't exists... I have written some classes in c++ before, and that is the first time anything like that happens to me... help please :(
You forgot to put ; after m_serial field variable. I believe this is the reason of the problem you have. Unfortunately many compilers do not give the exact reason of the problems like this, so you have to be careful with syntax rules.

C++ Constructor won't pass string - no constructor defined

I am trying to create an object of "Player" inside "PlayerManager" and I am getting the error in VS2010:
Error 1 error C2512: 'Player::Player' : no appropriate default constructor available c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory 631 1 Server
Player.h:
#ifndef _PLAYER_H
#define _PLAYER_H
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
Player(const string &name);
~Player(void);
private:
string name_;
};
#endif
Here is the constructor in Player.cpp:
Player::Player(const string &name)
{
}
PlayerManager.h:
'#ifndef _PLAYERMANAGER_H
#define _PLAYERMANAGER_H
#include <string>
#include <vector>
#include <iostream>
#include "Player.h"
using namespace std;
class PlayerManager
{
public:
PlayerManager(void);
~PlayerManager(void);
private:
vector<Player> players;
};
#endif'
Here is where I create the object in PlayerManager.cpp:
PlayerManager::PlayerManager(void)
{
Player test("Hello");
players.resize(1000);
for(int i=0; i < 960; i++){
players.push_back(test);
}
}
I don't understand why it is ignoring the string "Hello", I have tried creating a string object but gives same error.
I have also tried without adding the const & in the constructor but gives same error.
Any help would be appreciated, spend hours searching for an answer. Apologies if the layout is incorrect as this is my first time asking a question.
The class std::vector requires that the class you use it with has a default constructor1. You'll need to provide one for your class.
If you really don't want to provide one, you can give an instance of your class to vector in it's constructor call, so that it will use that instance instead of trying to default-construct one:
vector v(initialsize, Player("")); // or you can pass whatever string you want the default item to have
If the vector that you are using to store Players is a member variable, you'll need to pass it the default Player to use in the initialiser list:
PlayerManager::PlayerManager() : players(initialsize, Player("")) { // assuming the vector is named players
....
}
1 As R. Martinho Fernandes and Kerrek SB have pointed out in the comments, a default constructor is only required for this particular constructor of vector (the one that takes an initial size and when you don't give it a default instance) and the member function resize when called with a single argument. If you use the constructor that takes iterators or a const Allocator&, or if you use resize with the second argument, then you don't need a DC.

unexplained syntax error defining threadpool inside class definition

I have the following class definition and for some reason I cannot define the threadpool inside the class definition itself. It says: syntax error: identifier 'numberofpoolthreads' I tried directly defining it in the class, but it gives me same syntax error, does anyone know why this is?
#include "stdafx.h"
#include <boost/threadpool.hpp>
#include <boost/threadpool/pool.hpp>
#include <boost/threadpool/detail/pool_core.hpp>
typedef boost::threadpool::fifo_pool resolverpool;
class ResolverThreadPoolManager
{
public:
ResolverThreadPoolManager::ResolverThreadPoolManager(int numberofpoolthreads);
ResolverThreadPoolManager::~ResolverThreadPoolManager();
resolverpool p(numberofpoolthreads);
private:
int numberofpoolthreads;
};
This line: resolverpool p(numberofpoolthreads); isn't valid in a class definition. You need a member variable, which you then initialise in the constructor. e.g.:
class ResolverThreadPoolManager
{
public:
explicit ResolverThreadPoolManager(int numberofpoolthreads);
...
private:
const resolverpool p;
};
ResolverThreadPoolManager::ResolverThreadPoolManager(int numberofpoolthreads)
: p(numberofpoolthreads)
{}
In your line
resolverpool p(numberofpoolthreads);
the argument "numberofpoolthreads" is not a type, so this is a malformed declaration. Perhaps
resolverpool p(int numberofpoolthreads);
? I imagine, perhaps incorrectly, that your error message also hints on which line the error occurred, which can help narrow down where in a file an error lies. (Although, typically only indicating "error is on this or some previous line.")