No matching function for call to operator new - c++

I'm trying to wrap a class from a library I'm using in Lua. Specifially, I'm trying to wrap the color class from SFML. The full source for the color class can be seen here and here.
This is the function that's that I'm failing in.
int SFColor_new(lua_State* L)
{
// omitting part where I set r, g, b, and a
new (lua_newuserdata(L, sizeof(Color))) Color(r, g, b, a); // Line 47
luaL_getmetatable(L, LuaInfo<Color>::myMetaTableName);
lua_setmetatable(L, -2);
return 1;
}
And this is the error
LuaSFMLColor.cpp: In function ‘int ag::SFColor_new(lua_State*)’:
LuaSFMLColor.cpp:47: error: no matching function for call to ‘operator new(unsigned int, void*)’
<built-in>:0: note: candidates are: void* operator new(unsigned int)
make: *** [game] Error 1
I do similar things in a few other places without running into this error, so I'm not sure what would be causing it. Looking at the Color's source code I don't see anything weird or out of the ordinary, and I've run out of ideas. I've also tried using the default constructor (i.e. no arguments) and then just setting the value afterward, but that didn't do any good either.

To use the standard placement form of new you have to #include <new>.
The form of new that you are using requires a declaration of void* operator new(std::size_t, void*) throw();.
You don't have to #include <new> to use non-placement new.

The question has already been answered, but here's possible solution if you did #include <new> and still get error: no matching 'operator new' function for non-allocating placement new expression; include <new> on clang.
My code looked like this:
int* fun(const std::array<std::byte, 123>& param, std::size_t offset) {
return new(param.data()+offset) int;
}
When I switched to GCC, I got error: invalid conversion from 'const void*' to 'void*, which is significantly more useful. param must be passed by non-const reference.
It might seem obvious, but the original code was much more complex and it was difficult to spot the actual source of the issue.

Related

Troubles using fstream in a class

I get the following error, when compiling:
1>c:\users\ra\source\repos\sandbox\game\gamesetup_1\gamesetup_1\main.cpp(15): error C2280: 'DebugLib::DebugLib(const DebugLib &)': attempting to reference a deleted function
1>c:\users\ra\source\commonincludes\tannic\debuglib\debuglib.h(41): note: compiler has generated 'DebugLib::DebugLib' here
1>c:\users\ra\source\commonincludes\tannic\debuglib\debuglib.h(41): note: 'DebugLib::DebugLib(const DebugLib &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::basic_fstream<char,std::char_traits<char>>::basic_fstream(const std::basic_fstream<char,std::char_traits<char>> &)'
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.16.27023\include\fstream(1421): note: 'std::basic_fstream<char,std::char_traits<char>>::basic_fstream(const std::basic_fstream<char,std::char_traits<char>> &)': function was explicitly deleted
1>Done building project "GameSetup_1.vcxproj" -- FAILED.
The code looks like this:
DebugLib.h:
#include <string>
#include <fstream>
class DebugLib
{
public:
DebugLib(); // Reset timestamp etc.
~DebugLib(); // Flush output buffer
void Init(uint8_t output, std::string fileName = "debug.log"); // Initializes Log
void Log(int category, std::string msg); // Add a line to the log
void Flush(); // Output the remains of the Debug buffer
void Shutdown(); // Shut it down
private:
unsigned int m_initTime;
unsigned int m_bufferPos;
std::string m_outputBuffer[DEBUG_MAXSIZE];
std::fstream m_fileStream;
uint8_t m_output;
bool m_running;
};
main.cpp:
#include <iostream>
#include <DebugLib.h>
using namespace std;
int main()
{
DebugLib gDebugger = DebugLib();
gDebugger.Init(DEBUG_LOG_TO_SCREEN);
cout << "Running!" << endl;
gDebugger.Shutdown();
cin.get();
return 0;
}
As soon as I declare m_fileStream I get the error. Do I have a wrong declaration ?
When I remove all the use of m_fileStream in DebugLib.cpp, the code compiles fine, and runs (but of course not as attended)
I couldn't find a duplicate even though I've seen this asked before, so:
Let's start by explaining the error messages. I'll ignore the line numbers and error codes, as those are rarely useful until after you've understood (or at least read) the rest of the error message.
'DebugLib::DebugLib(const DebugLib &)': attempting to reference a deleted function
This is the main error: an attempt to use a function that is deleted, namely the copy constructor for DebugLib. Since you did not explicitly specify a copy constructor, it is up to the compiler to define one for you. The compiler will define a naive copy if possible. If this definition is not possible, it will delete the copy constructor for you.
As you noticed, the compiler is able to define a naive copy until you add a field that cannot be copied (such as std::fstream).
note: compiler has generated 'DebugLib::DebugLib' here
This is a clarifying note that helps the error refer to two lines in your program. The line number that came with the main error message is where you tried to do the copy, and the line number that comes with this note is where the copy constructor is generated. The compiler is trying to be helpful because it doesn't know which location you'll want to change to address this error.
note: 'DebugLib::DebugLib(const DebugLib &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::basic_fstream<char,std::char_traits<char>>::basic_fstream(const std::basic_fstream<char,std::char_traits<char>> &)'
This note explains the thing you noticed: copying your class is prevented because the std::fstream member cannot be copied. This message uses the name basic_fstream at this point, so it helps to know that fstream is an instantiation of the basic_fstream template. So that mess of code at the end of this note just names the copy constructor of std::fstream.
note: 'std::basic_fstream<char,std::char_traits<char>>::basic_fstream(const std::basic_fstream<char,std::char_traits<char>> &)': function was explicitly deleted
This is a further clarification. The line before this said "deleted or inaccessible". This line clarifies that to "explicitly deleted".
Now that we have read the error, we can go look at the lines to which it refers. The troublesome line is
DebugLib gDebugger = DebugLib();
This line requests that a DebugLib object be default constructed then copied to gDebugger. And there's the problem: it cannot be copied! The solution is to simplify your logic by removing the copy. You can invoked the default constructor directly on gDebugger. (This works for other constructors as well, should your code need them.)
DebugLib gDebugger{};
As a bonus, your code is shorter.

Unit testing a vector string

I have this really simple line of code in my production-code(A.cpp) as follows:
std::string A::getString(int i) {
return sVect_[i];
}
with the header as follows:
class A{
public:
std::string getString(int i);
...
private:
vector<std::string> sVect_;
...
};
I've been trying to test the getString() function using googletest but an error keeps popping out:
error: invalid conversion from 'char* (*)(const char*, int)throw ()' to 'int'
error: initializing argument 1 of 'std::string A::getString(i)'
This was my test program:
TEST(ATest, getString){
A a;
EXPECT_EQ("c", a.getString(i));
}
I couldn't quite grasp the workaround of the vector string and how to call it in my test program without ever changing the production code. I even use the hack, adding #define statements, to access the private member but still couldn't do it.
How do my test actually looks like to successfully call that function?
Note: I'm on Linux and using gcc. Thank you in advance guys.
Perhaps the error message is misleading. Have you defined i globally somewhere else? To me it looks like in the local scope because it does not know what the value of the variable i is, it is misbehaving in an unexpected way
TEST(ATest, getString){
A a;
EXPECT_EQ("c", a.getString(i)); //here what is the 'i' and where is it defined
}

Template function call ambiguity error

I am not familiar with templates. I've just started learning it. Why I am getting errors in following program?
#include <iostream>
#include <string>
using std::cout;
using std::string;
template<class C>
C min(C a,C b) {
return a<b?a:b;
}
int main()
{
string a="first string";
string b="second string";
cout<<"minimum string is: "<<min(a,b)<<'\n';
int c=3,d=5;
cout<<"minimum number is: "<<min(c,d)<<'\n';
double e{3.3},f{6.6};
cout<<"minimum number is: "<<min(e,f)<<'\n';
char g{'a'},h{'b'};
cout<<"minimum number is: "<<min(g,h)<<'\n';
return 0;
}
Errors:
13 [Error] call of overloaded 'min(std::string&, std::string&)' is ambiguous
6 [Note] C min(C, C) [with C = std::basic_string<char>]
Please help me.
There are a two things going on here.
Your first problem is that you only included part of the error message. Here is a link to the code being complied in gcc and clang, and one of the resulting error messages (in full):
main.cpp:13:34: error: call to 'min' is ambiguous
cout<<"minimum string is: "<<min(a,b)<<'\n';
^~~
/usr/include/c++/v1/algorithm:2579:1: note: candidate function [with _Tp = std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >]
min(const _Tp& __a, const _Tp& __b)
^
main.cpp:6:3: note: candidate function [with C = std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >]
C min(C a,C b) {
^
there are two candidates. One at main.cpp:6:3 (line 6, character 3) and one at algorithm:2579:1 (line 2579, character 1).
One of them you wrote, and one of them in #include <algorithm>.
One of your header files included <algorithm> without you asking for it. The standard headers are allowed to do this, as annoying as it is sometimes.
In <algorithm> there is a std::min function template. As std::string is an instance of a template class in namespace std, the function template std::min is found via a process called "argument dependent lookup" or "Koenig lookup". (function overload candidates are searched for locally, and also in the namespaces of the arguments to the function, and in the namespaces of the template arguments to the arguments to the function, and in the namespaces of the things pointed to by the arguments of the function, etc.)
Your local function min is also found, as it is in the same namespace as the body of main.
Both are equally good matches, and the compiler cannot decide which one you want to call. So it generates an error telling you this.
Both gcc and clang do error: then a sequence of note:s. Usually all of the note:s after an error are important to understanding the error.
To fix this, try calling ::min (fully qualifying the call), or renaming the function to something else, or make your version a better match than std::min (tricky, but doable in some cases), or calling (min)(a,b). The last blocks ADL/Koenig lookup, and also blocks macro expansion (for example, if some OS has injected #define min macros into their system headers) (via # 0x499602D2).
You're running into a name collision with std::min. It is likely included in one of the other standard libary headers that you included, either <iostream> or <string>, my guess is probably the latter. The quick fix is to rename your function. For example, renaming it to mymin works fine. Demo

error: expected primary-expression before ')' token (C)

I am trying to call a function named characterSelection(SDL_Surface *screen, struct SelectionneNonSelectionne sel) which returns a void
This is the .h of the function I try to call:
struct SelectionneNonSelectionne;
void characterSelection(SDL_Surface *screen, struct SelectionneNonSelectionne);
void resetSelection(SDL_Surface *screen, struct SelectionneNonSelectionne);
On my main function, I try to call it like this:
characterSelection(screen, SelectionneNonSelectionne);
When I compile, I have the message:
error: expected primary-expression before ')' token
I made the includes. I suppose I miscall the second argument, my struct. But, I can't find why on the net.
Have you got any idea about what I did wrong?
You should create a variable of the type SelectionneNonSelectionne.
struct SelectionneNonSelectionne var;
After that pass that variable to the function like
characterSelection(screen, var);
The error is caused since you are passing the type name SelectionneNonSelectionne
A function call needs to be performed with objects. You are doing the equivalent of this:
// function declaration/definition
void foo(int) {}
// function call
foo(int); // wat!??
i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing
int i = 42;
foo(i);
or
foo(42);
You're passing a type as an argument, not an object. You need to do characterSelection(screen, test); where test is of type SelectionneNonSelectionne.
I seen this problem with the latest nightly build of Code::Blocks. When I switched back to the stable release of Code::Blocks, 20.03 at the time of this writing, the problem went away and my code compiled and ran without problems. I'm not sure what Code::Blocks is doing, but it is very annoying. I got this repeatedly on a C++ project for every NULL in my code, forcing me to use nullptr instead.

Vector of pointer member functions c++

I have the following code:
typedef bool (A::*rule)(shared_ptr<Node >, shared_ptr<Node> ) ;
when initilaising the class A object, I run the following code
v_ = vector<rule>();
v_.push_back(A::memberFunction);
I have also tried with v_.push_back(&A::memberFunction) as this seemed more logical to me, but was
advised against on the forums. I also get an error message
This is as suggested by the many topics on the matter. However, I get the following error
non-const lvalue reference to type 'value_type' (aka 'bool (boost::shared_ptr<Node>, boost::shared_ptr<Node>)')
cannot bind to a temporary of type '<bound member function type>'
Does anyone know where I am going wrong?
I have also tried with v_.push_back(&A::memberFunction) as this seemed more logical to me, but was advised against on the forums.
I don't know what forums were those. Forming a pointer-to-member has a single valid syntax, and it is & classname::membername. All elements mandatory.
Use that consistently and post code and error message for that version should the problem persist.
This code compiles under llvm/clang 4.2 (As #balog-pal said, the & is mandatory before classname::membername:
#include <memory>
#include <vector>
struct Node {};
struct A
{
bool rule(std::shared_ptr<Node>, std::shared_ptr<Node>)
{return true;}
};
typedef bool (A::*rule)(std::shared_ptr<Node>, std::shared_ptr<Node> );
int main(int, const char**)
{
std::vector<rule> v;
v.push_back(&A::rule);
return 0;
}
Please post a full not-compiling example, your issue must be hidden somewhere else.