I have implemented my own wrapper around std::chrono::steady_clock and would like to prevent any other developer from using the original:
#include <iostream>
#include <chrono>
namespace my_chrono {
class MyClock : public std::chrono::steady_clock {
// stuff here...
};
}
int main()
{
auto my_now = my_chrono::MyClock::now(); // this should compile
auto chrono_now = std::chrono::steady_clock::now(); // this should be prevented
std::cout << my_now.time_since_epoch().count() << ", " << chrono_now.time_since_epoch().count() << std::endl;
return 0;
}
Unfortunately, I cannot find a way to force usage of MyClock over steady_clock (for example via compiler errors or warnings treated as errors).
You cannot make it impossible for some other code to be unable to use something you have no control over. And the C++ standard library is something over which you have no control.
Related
Is it possible to get the raw output as shown but with specific order(from bottom to top)?
cout<<R"(programming )";sleep(10); cout<<R"(
newbie at )";sleep(5); cout<<R"(
i'm )"; sleep(1);
output: programming------>printed third at the first line
newbie at------->printed second at the second line
i'm--------->printed first at the third line
Note: I don't mean reversing the output.
edit: as I guess the simple trick is to set their colour to black which will make them "disappear" and then by using nested for loop I can move through lines and change the colour of their one by one to white again with delay but i dont have an idea about how to do it practically
#include <chrono>
#include <future>
#include <iostream>
#include <thread>
int main()
{
using namespace std::chrono_literals;
auto print_first_line = std::async(std::launch::async, []() {
std::this_thread::sleep_for(6s);
std::cout << "programming\n" << std::flush;
});
auto print_second_line = std::async(std::launch::async, []() {
std::this_thread::sleep_for(3s);
std::cout << "newbie at\n" << std::flush;
});
auto print_third_line = std::async(std::launch::async, []() {
std::this_thread::sleep_for(1s);
std::cout << "i'm\n" << std::flush;
});
print_first_line.wait();
print_second_line.wait();
print_third_line.wait();
return 0;
}
As stated in the comments, it is not possible to control std::cout in this way. But it is possible to use threads to control the timing for you. This is a quick & dirty example of using std::async from <future> to multi-thread your print statements.
The first argument to std::async explicitly tells it to launch asynchronously as it can launch without creating a new thread. The second argument is a lambda with the sleep timer and the print statement.
It is worth noting that you will likely need an additional compiler argument. My current testing is in the WSL (Debian), so the compile command I'm using is clang++ -Wall -Wextra -pthread main.cpp where -pthread is the argument enabling multi-threading. For your platform it may be different.
As suggested, this scenario might be better served with a more generic function; something like delay_print(). Here's a possible implementation.
#include <array>
#include <chrono>
#include <cstdint>
#include <future>
#include <iostream>
#include <string>
#include <thread>
void delay_print(const std::chrono::duration<std::int64_t> &time,
std::string message)
{
std::this_thread::sleep_for(time);
std::cout << message << std::flush;
}
int main()
{
using namespace std::chrono_literals;
std::array<int, 4> seconds{7, 4, 2, 1};
std::array<std::string, 4> phrases{"How\n", "Now\n", "Brown\n", "Cow\n"};
auto print_line_01 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[0]), phrases[0]);
auto print_line_02 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[1]), phrases[1]);
auto print_line_03 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[2]), phrases[2]);
auto print_line_04 =
std::async(std::launch::async, &delay_print,
std::chrono::seconds(seconds[3]), phrases[3]);
print_line_01.wait();
print_line_02.wait();
print_line_03.wait();
print_line_04.wait();
return 0;
}
I am working on an old source code project which originally was written using MSVC 2008 and Boost 1.42, today I'm trying to port this to MSVC 2017 with Boost 1.73
There are many issues to resolve, one of which is below:
Severity Code Description Project File Line Suppression State
Error C3536 'binding': cannot be used before it is initialized Process Control Service Group processscope.cpp 197
The line that this occurs on:
auto binding = boost::bind(&IProcessChangeObserver::notify, _1, m_scope, change);
std::for_each(observers.begin(), observers.end(), binding);
Originally the assignment to binding was inline as the third parameter, it gives the same error. I can see why this is a problem, I cannot see why it ever worked?
Is there another way to write the above without the triggering a warning?
I've tried replacing with a standard loop:
for( std::list<boost::intrusive_ptr<IProcessChangeObserver> >::iterator itProc=objservers.begin();
itProc!=objservers.end(); itProc++ ) {
boost:bind(&IProcessChangeObserver::notify, itProc, m_scope, change);
}
To be honest I'm not 100% sure if this is a like for like replacement?
I have a suspicion the real problem is with binding which is likely not correctly initialized. There's bound to be more compiler messages about that.
It could be because Boost Bind stopped putting the _1 placeholders in the global namespace by default. You might detect this by adding -DBOOST_BIND_GLOBAL_PLACEHOLDERS to the compiler flags. However, heed the advice from the code:
BOOST_PRAGMA_MESSAGE(
"The practice of declaring the Bind placeholders (_1, _2, ...) "
"in the global namespace is deprecated. Please use "
"<boost/bind/bind.hpp> + using namespace boost::placeholders, "
"or define BOOST_BIND_GLOBAL_PLACEHOLDERS to retain the current behavior."
)
Minimal repro
See if you can reproduce with this minimal reproducer (I can't but I don't have access to the requisite versions ofr MSVC/Boost):
Live ON Coliru - GCC
Live On Rextester - MSVC
#include <algorithm>
#include <iostream>
#include <list>
#include <boost/bind/bind.hpp>
using namespace boost::placeholders;
#include <boost/intrusive_ptr.hpp>
#include <boost/smart_ptr/intrusive_ref_counter.hpp>
struct Scope {};
struct Change {};
namespace MyLib {
struct IProcessChangeObserver
: boost::intrusive_ref_counter<IProcessChangeObserver>
{
virtual ~IProcessChangeObserver() = default;
virtual void notify(Scope, Change) = 0;
};
struct Obs1 : IProcessChangeObserver {
void notify(Scope, Change) override { std::cout << "Obs1\n"; }
};
struct Obs2 : IProcessChangeObserver {
void notify(Scope, Change) override { std::cout << "Obs2\n"; }
};
}
using ObserverPtr = boost::intrusive_ptr<MyLib::IProcessChangeObserver>;
int main() {
using namespace MyLib;
std::list<ObserverPtr> observers {
new Obs1(), new Obs2(), new Obs1(),
};
Scope m_scope;
Change change;
auto binding = boost::bind(&IProcessChangeObserver::notify, _1, m_scope, change);
std::for_each(observers.begin(), observers.end(), binding);
}
Prints
Obs1
Obs2
Obs1
The actual fix was just to change _1 to std::placeholders::_1
I was attempting to follow the example of Finite State Filters in the Boost::iostreams documentation. However when I went to use the filter I got an error stating the ::imbue was not accessible because 'boost::iostreams::detail::finite_state_filter_impl' uses 'protected' to inherit from 'my_fsm'.
Frustrated I copied my code into the tests used to in the boost examples. The tests compile and pass. My conculsion is that I am probably mis-using the dual use filter defined by:
typedef io::finite_state_filter my_fsm_filter;
I feel that just pushing it onto a filtered_stream may not be proper, but I could not find a missing step. I am sure there must be a need to wrap the filter but I can find no example (though I am sure if I dug deep enough into the code used to test the boost code it has to be there somewhere).
here is a bit of example code:
#include <boost/mpl/vector.hpp>
#include <libs/iostreams/example/finite_state_filter.hpp>
namespace io = boost::iostreams;
struct my_fsm : io::finite_state_machine<my_fsm> {
BOOST_IOSTREAMS_FSM(my_fsm) // define skip and push.
typedef my_fsm self;
static const int beginline = 0;
static const int skipline = 1;
static const int dataline = 2;
typedef boost::mpl::vector <
row<beginline, is<'C'>, skipline, &self::skip>,
row<beginline, is_any, dataline, &self::push>,
row<skipline, is<'\n'>, beginline, &self::skip>,
row<skipline, is_any, skipline, &self::skip>,
row<dataline, is<'\n'>, beginline, &self::push>,
row<dataline, is_any, dataline, &self::push>
> transition_table;
};
typedef io::finite_state_filter<my_fsm> my_fsm_filter;
#include <iostream>
#include <string>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;
int main() {
io::stream<io::file_sink> out(io::file_sink("outputfile.txt"));
io::filtering_istream in;
my_fsm_filter infsm;
in.push(my_fsm_filter());
in.push(io::file_source("inputdata.txt"));
while (in) {
std::string line;
if(std::getline(in, line)) {
//std::cout << line << std::endl;
out << line << std::endl;
}
}
return 0;
}
I personally feel that there is a bug in the sample header with respect to this imbue call.
However, you can work around it by changing the typedef to
struct my_fsm_filter : io::finite_state_filter<my_fsm> {
using io::finite_state_filter<my_fsm>::imbue;
};
This explicitly exposes the imbue method as public on the derived type. I haven't looked at the sample program that you reported to be working (because you didn't link to it). But it's possible they used a similar hack.
In my tests, a similar edit to finite_state_filte.hpp L278 to add
using base_type::imbue;
to class finite_state_filter has the same effect.
This is really driving me crazy:
#include <iostream>
#include <vector>
#include <string.h>
#include <thread>
using namespace std;
void test() {
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
}
int main() {
thread(test).join();
return 0;
}
The code compiles fine with the -std=c++11 flag to the compiler and the -pthread flag to the linker.
BUT: Eclipse does either know the std::thread or the myvector.begin()->length(), even if the code runs fine eclipse warns me "Method 'length' could not be resolved".
I tried every possible solution in here: Eclipse CDT C++11/C++0x support without any success. This took me so many hours now, what am I doing wrong?!
Is there anybody getting a project setup without problems with this code?
EDIT: Other code example - same problem:
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
class TestClass {
public:
void test() {
cout << "test" << endl;
}
};
void test() {
vector<TestClass> testClassVector;
TestClass x;
testClassVector.push_back(x);
testClassVector.begin()->test();
}
int main() {
thread(test).join();
return 0;
}
Compiles and runs correct, but returns in eclipse: Method 'test' could not be resolved
EDIT:
working versions:
((TestClass)*(testClassVector.begin())).test();
TestClass foo2 = *(testClassVector.begin());
foo2.test();
still not working:
testClassVector.begin()->test();
The last compiles and works like the two above, but eclipse still claims:
Method 'test' could not be resolved
Maybe I'm wrong, but I think your problem don't come from Eclypse. Juste, begin() on a vector return a std::vector<T>::iterator first, this is not a pointer and there is no method length, but you can ask for the vector size with myvector.size(); if this is what you want.
The problem could come from your #include <string.h> that is not the same as #include <string>, string.h is for string operation like strcmp, strstr, etc... juste string will define the std::string object.
I don't have Eclipse set up but the problem appears to be around std::string. Does the problem go away if you remove the threading from the example? (I also changed to #include <string> instead of string.h)
#include <iostream>
#include <vector>
#include <string>
#include <thread>
using namespace std;
#if 0
void test() {
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
}
#endif
int main() {
//thread(test).join();
vector<string> myvector;
string a("Teststring");
myvector.push_back(a);
cout << myvector.begin()->length() << endl;
return 0;
}
That should hopefully print out 10.
Update from comment:
Does this generate the Eclipse warning?
auto tmp = *(myvector.begin());
std::cout << tmp.length() << std::endl;
What about this?
std::string foo("abc123");
std::cout << foo.length() << std::endl;
I guess one more too:
std::string foo2 = *(myvector.begin());
std::cout << foo2.length() << std::endl;
The solution found:
I downloaded eclipse kepler Kepler
Created a new project and tried to compile this source code (like above):
#include <iostream>
#include <vector>
#include <thread>
using namespace std;
class TestClass {
public:
void test() {
cout << "test" << endl;
}
};
void test() {
vector<TestClass> testClassVector;
TestClass x;
testClassVector.push_back(x);
testClassVector.begin()->test();
}
int main() {
thread(test).join();
return 0;
}
On the first run eclipse told me, thread belongs to the new c++11 standard and I have to add -std=c++11 to the compiler flags. To use thread I also added -pthread to the linker flags. With this steps the code could be compiled, but eclipse marks the thread still as unknown. To fix this I proceeded the following step:
Under C/C++ Build (at project settings), find the Preprocessor Include Path and go to the Providers Tab. Deselect all except CDT GCC Builtin Compiler Settings. Then untag Share settings entries … . Add the option -std=c++11 to the text box called Command to get compiler specs.
Found here.
Now - unbelievable but true - it works, even without any errors marked by eclipse. The solution is using the (beta) version of eclipse, wich seems to handle this in a better way.
Thanks for all your help!
struct test_struct
{
test_struct() {}
~test_struct() {}
};
#include <vector>
#include <memory>
#include <cstdio>
int main()
{
printf("ctor begin\n");
{
std::vector<std::unique_ptr<test_struct>> test_vec;
const int count = 100000;
for (auto i = 0; i < count; i++) {
test_vec.emplace_back(new test_struct);
}
printf("dtor begin\n");
}
printf("dtor end\n");
}
I'm using VS2010, and found some ridiculous performance issue. The code above works well both in debug and release build (ctrl+f5), but when debugger is attached(f5), dtor call for unique_ptr class is intolerably slow. The result machine code is fairly optimized, so I don't expect that it's compiler issue rather than debugger's, but I don't know how to deal with it. My question is
Is this problem able to be reproduced on your machine?
What's the reason of this behaviour?
Is there any workaround?
The slowdown is caused by memory checking that occurs whenever memory is freed. However, this is a special system-/debugger-level heap, and isn't anything you can control from within your program.
There's a great article on the issue. To summarize: you have to set an environment variable to disable it!
Luckily, you can set project-specific environment variables from the Debugging options in the Project Settings for your project, so that the environment variable is only applied to your program.
I used this simplified program to test:
#include <iostream>
#include <memory>
#include <vector>
int main()
{
std::cout << "ctor begin" << std::endl;
{
std::vector<std::unique_ptr<int>> test_vec;
for (unsigned i = 0; i < 100000; i++)
test_vec.emplace_back(new int);
std::cout << "dtor begin" << std::endl;
}
std::cout << "dtor end" << std::endl;
}
By setting _NO_DEBUG_HEAP=1 as an environment variable (either system-wide, which I won't recommend, or through the Debugging options), the code runs in roughly the same amount of time irrespective of whether or not the debugger is attached.