I am trying to create a class which can read input from either a file stream or std::cin:
#include <string>
#include <iostream>
#include <mutex>
class A
{
public:
explicit A(std::istream& input)
: input_(input)
{
;
}
public:
void doSomething()
{
std::string word;
while (input_ >> word) {
std::cout << word << std::endl;
}
}
private:
std::istream& input_;
std::mutex mutex_;
};
int main()
{
auto a = A(std::cin);
a.doSomething();
return 0;
}
But the compiler gives the following output:
~/test/main.cpp: In function ‘int main()’:
~/test/main.cpp:31:22: error: use of deleted function ‘A::A(A&&)’
auto a = A(std::cin);
^
~/test/main.cpp:5:7: note: ‘A::A(A&&)’ is implicitly deleted because the default definition would be ill-formed:
class A
^
~/test/main.cpp:5:7: error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’
In file included from /usr/include/c++/7/mutex:43:0,
from ~/test/main.cpp:3:
/usr/include/c++/7/bits/std_mutex.h:97:5: note: declared here
mutex(const mutex&) = delete;
^~~~~
How should I fix the error? Or generally, how do we create a class that can read input either from a file stream or std::cin?
Edit
Initially I tried to reduce the amount of code as much as possible, and in that process, I removed std::mutex part, which gave a very different compiler output. Plus, there was a typo where input_ was std::stream and #JerryJeremiah was correct in the first comment that it should be std::istream &.
Now, I think the question doesn't quite match the problem, as #acraig5075 also pointed out in the comment. And there are similar questions on Stack Overflow already, so I'm going to delete my question.
I found the answer.
std::mutex is not copyable, and the class containing it becomes not-copyable as well.
The code should be:
int main()
{
A a(std::cin);
a.doSomething();
return 0;
}
Related
sorry for the verbosity - I did my best to condense my code sample into a minimally functional class and main() method.
I'm trying to use an atomic_flag to notify _rx() within my worker thread to quit when stop() is called.
I believe the issue is in trying to create my worker thread,
thread SanityTestThread(&SanityTest::_rx, *this);
which somehow clashes with my atomic_flag
code sample (does not compile):
#include <cstdio>
#include <chrono>
#include <unistd.h>
#include <atomic>
#include <iostream>
#include <thread>
using namespace std;
class SanityTest
{
public:
SanityTest(){}
void start();
void stop();
private:
void _rx();
atomic_flag flag;
}; // end class SanityTest
void SanityTest::_rx()
{
while(flag.test_and_set())
{
this_thread::sleep_for(chrono::seconds(1));
cout << "'sup foo" << endl;
}
} // end _rx
void SanityTest::start()
{
flag.test_and_set();
thread SanityTestThread(&SanityTest::_rx, *this);
SanityTestThread.detach();
} // end start
void SanityTest::stop()
{
flag.clear();
} // end start
int main(){
SanityTest s;// = SanityTest();
s.start();
this_thread::sleep_for(chrono::seconds(10));
s.stop();
return 0;
} // end main
For the record, I can get my program to compile and run by removing all references to my atomic_flag and replacing my _rx() loop with a for loop like so:
void SanityTest::_rx()
{
for(int i=0; i <=10; ++ i)
{
this_thread::sleep_for(chrono::seconds(1));
cout << "'sup foo" << endl;
}
} // end _rx
Compiler Error:
In file included from ./SanityTest.cpp:1:0:
./SanityTest.hpp:14:7: note: ‘SanityTest::SanityTest(SanityTest&&)’ is implicitly deleted because the default definition would be ill-formed:
class SanityTest
^
./SanityTest.hpp:14:7: error: use of deleted function ‘std::atomic_flag::atomic_flag(const std::atomic_flag&)’
In file included from /usr/include/c++/4.8/atomic:41:0,
from ./SanityTest.hpp:8,
from ./SanityTest.cpp:1:
/usr/include/c++/4.8/bits/atomic_base.h:275:5: error: declared here
atomic_flag(const atomic_flag&) = delete;
^
In file included from /usr/include/c++/4.8/functional:55:0,
from /usr/include/c++/4.8/thread:39,
from ./SanityTest.hpp:10,
from ./SanityTest.cpp:1:
...
In file included from ./SanityTest.cpp:1:0:
./SanityTest.hpp:14:7: note: ‘SanityTest::SanityTest(SanityTest&&)’ is implicitly deleted because the default definition would be ill-formed:
class SanityTest
^
./SanityTest.hpp:14:7: error: use of deleted function ‘std::atomic_flag::atomic_flag(const std::atomic_flag&)’
In file included from /usr/include/c++/4.8/atomic:41:0,
from ./SanityTest.hpp:8,
from ./SanityTest.cpp:1:
/usr/include/c++/4.8/bits/atomic_base.h:275:5: error: declared here
atomic_flag(const atomic_flag&) = delete;
^
In file included from /usr/include/c++/4.8/functional:55:0,
from /usr/include/c++/4.8/thread:39,
from ./SanityTest.hpp:10,
from ./SanityTest.cpp:1:
p.s. This is compiled with, g++ -pthread -std=c++0x -o SanityTest ./SanityTest.cpp
Just replace
thread SanityTestThread(&SanityTest::_rx, *this);
with
thread SanityTestThread(&SanityTest::_rx, this);
You probably intended to pass a pointer to the object and not the object itself (which would result in that object being copied and the member function pointer &SanityTest::_rx being invoked on that copy instead of the original object).
The reason for the error message is essentially that std::atomic_flag doesn't have a copy constructor and so the compiler doesn't generate a default one for your SanityTest class either, but again: you don't want to copy your SanityTest object here anyway.
I am facing an error in one of my projects which I have replicated using a standalone program. I did see several posts pertinent to this, but could not figure out my problem. I am getting the following error with this code : "error: expected constructor, destructor, or type conversion before '&' token"
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
class X
{
private:
int _x;
public:
X(int x) : _x(x) {};
};
class Y
{
private:
typedef boost::shared_ptr<X> X_ptr;
public:
X_ptr& func1();
};
X_ptr& Y::func1()
{
X_ptr p(new X(8));
return p;
};
int main()
{
return 0;
}
Can someon help me with in resolving this error?
There are two problems. First, you forgot to qualify the type name X_ptr:
Y::X_ptr& Y::func1()
// ^^^ ^
// BUT REMOVE THIS!
Second, notice that you are returning a reference to a local variable. Attempting to dereference the value returned by func1() will give you undefined behavior.
Just change the prototype of your function this way:
Y::X_ptr Y::func1()
// ^^^^^
// Returning the smart pointer by value now
{
X_ptr p(new X(8));
return p;
}
I have this code:
hpp:
#include <list>
using namespace std;
class funcionario
{
public:
struct Dia {
int d;
int h;
int id;
int tipo;
};
funcionario ();
void eliminar(int dia, int hora);
private:
list<Dia> agenda;
};
cpp:
#include "myClass.hpp"
funcionario::funcionario(){
agenda = list<Dia> ();
}
void funcionario::eliminar(int dia, int hora) {
list<funcionario::Dia>::iterator it;
it = agenda.begin();
while(it != agenda.end() && (*it).d <= dia) {
if((*it).d == dia && (*it).h == hora) {
agenda.erase(it);
return;
}
++it;
}
}
I get this compiling error:
Funcionario.cpp: In constructor ‘funcionario::funcionario()’:
Funcionario.cpp:5: error: cannot convert ‘std::list<funcionario::Dia, std::allocator<funcionario::Dia> >’ to ‘int’ in assignment
Funcionario.cpp: In member function ‘void funcionario::eliminar(int, int)’:
Funcionario.cpp:9: error: request for member ‘begin’ in ‘((funcionario*)this)->funcionario::agenda’, which is of non-class type ‘int’
Funcionario.cpp:10: error: request for member ‘begin’ in ‘((funcionario*)this)->funcionario::agenda’, which is of non-class type ‘int’
Funcionario.cpp:11: error: request for member ‘end’ in ‘((funcionario*)this)->funcionario::agenda’, which is of non-class type ‘int’
I don't know what I'm doing wrong.
Not sure what you're trying to achieve, but the code just needs to be fleshed out a bit with complete function definitions. I got this to compile:
#include <list>
class myClass
{
public:
myClass();
struct myStruct {
int myInfo;
};
void something();
void doSomething(myStruct & ms);
private:
std::list<myStruct> myList;
};
myClass::myClass(){
myList = list<myStruct> ();
}
void myClass::something() {
std::list<myStruct>::iterator it;
it = myList.begin();
while(it != myList.end()) {
doSomething(*it);
++it;
}
}
Incidentally (or maybe directly relevant, not sure) - the copy-initialization of myList in myClass() is unnecessary, as others have stated. The list<> default constructor will do the right thing, and more efficiently.
This seems to be working on my computer, so may it be a compiler problem? Try with another compiler and tell us if it worked
The initialization you're looking for is analogous to Initializing map and set class member variables to empty in C++? - but actually you'll get an empty list automatically (i.e. by the std::list default constructor).
--Edited to reflect your posting of the original code--
H is not declared anywhere.
and is not a valid C++ keyword or token. Use &&.
Use the local header include form of : #include "myClass.hpp"
I am trying to implement the a map from the C++ STL as follows:
#include <string>
#include <iostream>
#include <map>
using namespace std;
#include "assembler.h"
// This Class makes use of the Map Template from the Standart Template Library
// All addresses are stored as numerical (Dec) integers
SymbolTable::SymbolTable() { // Constructor
map <string, int> symbolTable;
int address = 0;
}
void SymbolTable::addEntry(string symbol, int address) {
symbolTable[symbol] = address;
address++;
}
// Returns true if symbolTable already contains symbol
bool SymbolTable::contains(string symbol) {
if (symbolTable.find(symbol) == symbolTable.end()) { return true; }
else { return false; }
}
int SymbolTable::getAddress(string symbol) {
return symbolTable[symbol];
}
I try to compile this with
c++ *.cpp -0 assembler.out
and I get the following error message:
symboltable.cpp:57:9: error: no viable conversion from 'mapped_type' (aka 'std::basic_string<char>') to 'int'
return symbolTable[symbol];
^~~~~~~~~~~~~~~~~~~
1 error generated.
I have searched for this error online and all I get is bug reports relating to the STL and I cannot figure out if those reports are the same problem I am having and if so how to get around it. Am I doing something wrong?
I have tried (probably stupidly) to typecast the offending line as
return (int) symbolTable[symbol];
Thank you for any help.
My header file declares the class as:
class SymbolTable {
public:
SymbolTable();
void addEntry(string, int);
bool contains(string);
int getAddress(string);
private:
map <string, string> symbolTable;
int address;
};
This:
SymbolTable::SymbolTable() { // Constructor
map <string, int> symbolTable;
^
^
is a function-local variable, not a member variable. It is not the same as the symbolTable that you're accessing in e.g. getAddress, which presumably is a member variable. You haven't shown the class body, but my guess is that it's defined differently.
I'm getting this error on line 6:
error: expected unqualified-id before '{' token
I can't tell what's wrong.
#include <iostream>
using namespace std;
class WordGame;
{ // <== error is here on line 6
public:
void setWord( string word )
{
theWord = word;
}
string getWord()
{
return theWord;
}
void displayWord()
{
cout << "Your word is " << getWord() << endl;
}
private:
string theWord;
}
int main()
{
string aWord;
WordGame theGame;
cin >> aWord;
theGame.setWord(aWord);
theGame.displaymessage();
}
There should be no semicolon here:
class WordGame;
...but there should be one at the end of your class definition:
...
private:
string theWord;
}; // <-- Semicolon should be at the end of your class definition
As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.
void setWord(const std::string& word) {
theWord = word;
}
Get rid of the semicolon after WordGame.
You really should have discovered this problem when the class was a lot smaller. When you're writing code, you should be compiling about every time you add half a dozen lines.
Semicolon should be at the end of the class definition rather than after the name:
class WordGame
{
};
For what it's worth, I had the same problem but it wasn't because of an extra semicolon, it was because I'd forgotten a semicolon on the previous statement.
My situation was something like
mynamespace::MyObject otherObject
for (const auto& element: otherObject.myVector) {
// execute arbitrary code on element
//...
//...
}
From this code, my compiler kept telling me:
error: expected unqualified-id before for (const auto& element: otherObject.myVector) {
etc...
which I'd taken to mean I'd writtten the for loop wrong. Nope! I'd simply forgotten a ; after declaring otherObject.
For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true in place of simply true, like this:
bool my_var = my_first_scope::my_second_scope::true;
instead of:
bool my_var = true;
This is because I had a macro which caused MY_MACRO(true) to expand into my_first_scope::my_second_scope::true, by mistake, and I was actually calling bool my_var = MY_MACRO(true);.
Here's a quick demo of this type of scoping error:
Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):
#include <iostream>
#include <cstdio>
namespace my_first_scope
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope
int main()
{
printf("Hello World\n");
bool my_var = my_first_scope::my_second_scope::true;
std::cout << my_var << std::endl;
return 0;
}
Output (build error):
main.cpp: In function ‘int main()’:
main.cpp:27:52: error: expected unqualified-id before ‘true’
bool my_var = my_first_scope::my_second_scope::true;
^~~~
Notice the error: error: expected unqualified-id before ‘true’, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::) scope operator I have just before true.
When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):
#define MY_MACRO(input) my_first_scope::my_second_scope::input
...
bool my_var = MY_MACRO(true);
I get this new error instead:
main.cpp: In function ‘int main()’:
main.cpp:29:28: error: expected unqualified-id before ‘true’
bool my_var = MY_MACRO(true);
^
main.cpp:16:58: note: in definition of macro ‘MY_MACRO’
#define MY_MACRO(input) my_first_scope::my_second_scope::input
^~~~~
I got this error because I was not declaring a variable and was using it further .
Here is my code why I was getting it.
It was because I was not declaring a variable for size of my >vector.
Just replace
int n=arr.size();
Replace Here,
int sumSubarrayMins(vector<int>& arr) {
int = arr.size();
long long sum;
long long ans =0;
for(long i =0;i<n;i++){
sum =0;
long mini=INT_MAX;
for(long long j =i;j<n;j++){
mini=min(mini,arr[j]);
sum+=mini;
}
ans+=sum;
}
return ans;
}