mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The problem is that you cannot run code in the global scope. The global scope is only for declarations or definitions, not for expressions (executing code). You have to move your setting for the Printed functor in the main function:

#include <iostream>
#include <string>
#include "events.h"

using namespace std;

class test
{
    public:
    events<> Printed{[]() { ; }};
    void write(string a)
    {
        cout << a;
        Printed();
    }

};


int main()
{
    test a;

    a.Printed = events<>{[]()
    {
        cout << "\nMessage printed\n";
    }};

    a.write("hello world");
    cin.get();
    return 0;
}

I think this should work, although I have no idea how "events" is set up.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The way this is done is quite simple. It's all a matter of creating an interface (i.e., set of functions or classes) that is not specific to any particular platform. Then, you create an implementation that fulfills that interface for each platform you want to support in a way that hides all the platform-specific code. This way, you need to compile your library for each platform, but for the user of the library, it all appears to be the same because the user only interacts with the interface (not with the encapsulated implementation details).

If you take the example of SDL. The Unix/Linux/Mac API for creating and dealing with a window is very different from the Win32 API used in Windows. However, in abstract terms, they do the same things, e.g., create a window, set some pixel values on it, have "redraw" events, etc... So, the SDL library has created a set of abstractions, like SDL "surfaces", that encapsulate those essential and common functionalities between the platforms. So, as a user of SDL, you only have to deal with those, and you can remain oblivious to the implementation details (i.e., what actual API calls are done under-the-hood). Then, the SDL implementers simply create source files (.c, .cpp files) for each platform, and that use the correct API calls to fulfill the "contract" or functionality that is exposed by the platform-agnostic interface.

This is really the key to creating a cross-platform library that requires the use of platform-specific API calls. You …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Read this tutorial and you'll understand what the problem is with that code.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For video capture, I just use RecordItNow.

For snapshot, I just use the "print screen" button, which pops up the KSnapshot utility.

As you may have guessed from those links, I use Linux with KDE as desktop environment.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Insurance is based on the fact that the majority of insured persons won't use the majority of services they are insured for

That's one component of it. The other component of insurance is bargaining power. Technically, you could create a one-man insurance company, which would essentially amount to stuffing money under your mattress (figuratively), for the rainy days. But when you do get unlucky and need that money to pay for some medical care, you'll have to go around shopping for the best deal from one hospital to the next. The problem with that is that you have no bargaining power because you are a single individual and you are in a desparate state. In other words, they will be able to charge you almost anything they want, and indeed, they do.

Arguably, the single most important role that the insurer plays is to act as a force to be rekon with at the negociation tables (its force comes from its number of members), and is thus able to negociate much more advantageous prices for the care being delivered. By far the insurer with the most bargaining power in the US is Medicare, and this is why its far more efficient and low-cost than any competing private insurance company.

Last I checked, there were well over 100 benefits unique to women (that men are required to subsidize, recall). Conversely, male-specific benefits was 0. This is hardly fair, and I question half the population being forced …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You have to iterate through the elements of the vector and output each string to the file.

Here's one way:

std::ofstream file_out("filename.txt");
std::copy(v.begin(), v.end(),
          std::ostream_iterator<std::string>(file_out, "\n"));

Here's another:

std::ofstream file_out("filename.txt");
for(const auto& s : v)
  file_out << s << std::endl;

Here's another:

std::ofstream file_out("filename.txt");
for(auto it = v.begin(); it != v.end(); ++it)
  file_out << *it << std::endl;

Here's another:

std::ofstream file_out("filename.txt");
for(std::size_t i = 0; i < v.size(); ++i)
  file_out << v[i] << std::endl;

There's really not much to it. Pick what you are most comfortable with.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

!Three Amigos!

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That's the irony. Laws that require communications to be "tappable" are there to allow law enforcement to be able to tap into it if they can show cause (get a warrant), which is perfectly fine. But now that they have obscenely abused of their capabilities to tap into people's communications, people will flock towards 100% secure ("untappable") means of communication, including the "bad guys", making catching the bad guys much harder.

This kind of "hide and seek" game is untenable. When an agency like the NSA starts tapping into all "normal" communication channels, all the people communicating anything of real interest to the agency will do so on a more secure channel, leaving the agency to waste its time processing meaningless / uninteresting chatter. Then, they'll want access to the more secure channels, leaving the people of interest to hide in another place. Sure, you might catch a few people by surprise, but it's like trying to catch cockroaches with a spotlight.

And in the mean time, people's privacy is stampeded, and constitutions or human rights charters are befouled. And all sorts of collateral abuses are perpetrated.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You could do something like this:

thread-1              thread-2
LOCK(GETNAME)            
DBName = getNewDBName()
DBName == "Y_server_fwd_10"
UNLOCK(GETNAME)          
YIELD         --->    
                      LOCK(GETNAME)
                      DBName = getNewDBName()
                      DBName == "Y_server_fwd_11"
                      UNLOCK(GETNAME)
                      pDB = new DB(DBName)
                      pDB->index(..)
              <---    YIELD
pDB = new DB(DBName)
pDB->index(..)
LOCK(ADDDB)
addDBToGroup(pDB)
UNLOCK(ADDDB)
YIELD         --->    
                      LOCK(ADDDB)
                      addDBToGroup(pDB)
                      UNLOCK(ADDDB)

The point here is that the two operations that you really need to "lock" are (1) obtaining a new and unique name for a new database, and (2) adding the new database to the group of databases. The creation of the database (construction, and allocation with "new") is something that is independent between threads, since each thread deals with its own database. Similarly for the indexing of the image into the database. So, you could lock a function that returns a new unique name for a new database (that also increments the "count" that is used to generate it), and then lock a function to add a database to the group. And then, everything else can be done concurrently (presumably, the most expensive operations are the creation of the database and the indexing of an image, not those two small operations that are locked).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The operator -- is just the decrement operator, i.e., the opposite of ++.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is what I think is happening:

thread-1              thread-2
LOCK(READ)            
read numDBs == X      
UNLOCK(READ)          
YIELD         --->    LOCK(READ)
                      read numDBs == X
                      UNLOCK(READ)
                      LOCK(WRITE)
                      create DB: "Y_server_fwd_X"
                      result <- getDB("Y_server_fwd_X")
                      UNLOCK(WRITE)
                      return result
LOCK(WRITE)   <---    YIELD
create DB: "Y_server_fwd_X"
get DB("Y_server_fwd_X")
result <- getDB("Y_server_fwd_X")
UNLOCK(WRITE)
return result

As you can see, the problem is in the fact that two threads might, concurrently, find the same amount of databases in the group, leading to both threads creating a database with the same name. Presumably, when you "get" the database pointer again by looking it up by name, you will get the same pointer in both cases, leading to the indexing of multiple images to the same database.

You need to have a lock over the entire operation. In this case, the simpler solution seems to be the best, just lock the entire operation with one mutex, instead of this complicated scheme.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

This is a Visual C++ (or "MSVC", for short) extension. This line tells the compiler (if it can understand it) to link with the "gdi32.dll" library. The GCC compiler (MinGW, that Codeblocks uses) does not support this "automatic linking" feature. You must specify the library manually in your project configuration.

I don't know Codeblocks that well off the top of my head, so I can't guide you through the menus, but you should be able to find a place in the Linker configuration for adding additional libraries.

As for which library to link to, I believe that MinGW comes with an import library called libgdi32.a to link to the dynamic library gdi32.dll.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think what you should use is the std::thread class, see docs here. You would get the following:

#include <process.h>
#include <string>
#include <thread>

using namespace std;


void SetCaretPosition (int x, int y)
 {
     COORD coord; // coordinates
     coord.X = x; coord.Y = y; // X and Y coordinates
     SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); // moves to the coordinates
 }

COORD GetCaretPosition()
{
    COORD s;
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    s.X=csbi.dwCursorPosition.X;
    s.Y=csbi.dwCursorPosition.Y;
    return s;
}

struct Blink
{
    string Text;
    int x;
    int y;
    int TextColor;
    int BackColor;
};

void BlinkLoop(const Blink& b)
{
    char *EmptyText;
    EmptyText=new char[ b.Text.length() ] ;
    int i;
    for(i = 0; i <= b.Text.length(); i++)
    {
        EmptyText[i] = ' ';
    }
    EmptyText[i] ='\0';
    HDC a = GetDC(GetForegroundWindow());
    while (true)
    {
        TextOut(a, b.x, b.y, b.Text.c_str(), b.Text.length());
        Sleep(1000);
        TextOut(a, b.y, b.x, EmptyText, b.Text.length());
        Sleep(500);
    }
}

void TextBlink(string Text, int x, int y, int TextColor, int BackColor)
{
    Blink b;
    b.Text=Text;
    b.BackColor=BackColor;
    b.TextColor=TextColor;
    b.x=x;
    b.y =y;
    std::thread t(BlinkLoop, std::cref(b));
}

which will have exactly the desired effect of your original code.

If you can't use std::thread because your compiler is too old, then just use Boost.Thread library.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

That function could have been written like below, where x is an unitialized variable until it is set to the parameter.

Absolutely not! If you think that, you did not get the point, at all!

If I use the implementation you provided into this program:

#include <iostream>

int get_first_value(int value) {
  static int x;
  x = value;
  return x;
};

int main() {
  std::cout << get_first_value(42) << std::endl;
  std::cout << get_first_value(69) << std::endl;
};

then, the resulting output is:

$ ./test_static_local
42
69

If I use my original implementation:

#include <iostream>

int get_first_value(int value) {
  static int x = value;
  return x;
};

int main() {
  std::cout << get_first_value(42) << std::endl;
  std::cout << get_first_value(69) << std::endl;
};

then, the output is:

$ ./test_static_local
42
42

You can try it for yourself, you are skeptic about it.

Because the value of x is initialized the first time control flows over it, that is, with the value 42 (which is passed on the first call). So, on the second call, even though 69 is passed, the value of x remains the same, i.e., 42, because the variable is already initialized, and won't be initialized again.

The get_first_value() function he posted is not initializing x, it is just simply setting x to the value of the parameter. That isn't the same thing as initializing x.

By "initialized", I mean initialized, as defined in the standard, which means, it is constructed (i.e., …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@rubberman: It is more than a lot more efficient, it is, as I said, exponentially faster. Here is a graph of the performance of nearest-neighbor queries in a DVP-tree (which is a kind of metric-space partitioning tree, which is very similar to a BST, just with more complicated splitting logic). The DVP-tree implementation is identical in both cases, only the tree storage data structure is different (Graph == linked-tree structure, and B-Tree == breadth-first layout in a contiguous array (vector)). As seen, when relying on a linked-structure, it barely matches up with linear search (i.e., it's initially O(log(n)) but ends up at O(n) complexity), and when relying on contiguous storage, it's logarithmic O(log(n)) performance. The difference is purely due to cache thrashing when using a linked-structure. This is why I say it is exponentially faster when you have cache-friendly storage and predictable memory-access patterns.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I think you need quotes around the whole thing:

system("del \"%APPDATA%\\Microsoft\\Windows\\Start Menu\\*.vbs\"");

That's the way to deal with that (when there are spaces anywhere in the file-path).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yes, it's true that diesel is often a bit more expensive than gas, but it also takes less diesel to get the same energy out. It actually ends up being cheaper, when considering things on a equal-power basis. Diesel fuel is 11% more dense in energy than gasoline fuel. And diesel engines are usually quite a bit more efficient than gasoline engines (this is due to the fundamental principle of the engine, which results in higher burning temperature and higher compression, which results in a higher efficiency, this is a result of thermodynamics, you can look up the calculations). Overall, modern diesel engines will consume between 20% and 40% less liters of fuel than modern gasoline engines. This is why they have been used for years in trucks and busses and stuff, it's because it's more economical, and it has always been (only now is the technology good enough to mitigate certain problems with older diesel engines, such as the smell and the large and heavy engine blocks required for the long / high-compression cylinders).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

@naysa: Don't hijack an old thread like this. You should make a new thread to ask your question. And don't forget to show some efforts of your own towards solving your problem. We don't just provide ready-made answers to people's homework assignments.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I know of no US made autos that run on diesel

There are some. At least, cars that are sold in the US. As for being made in the US, well, even cars from US companies are often not made in the US anymore, so, that's rare either way.

Volkswagen has had diesel cars (or a diesel option on many models) for a long time (I don't know how popular in the US, but very common here, north of the border). My father has a fairly new Jetta TDI, and it runs like a charm and makes good mileage (I don't know the exact number, but I think it is around 5L/km, or around 50mpg).

Here in Canada, diesel is often a little bit more expensive than normal gasoline. Sometimes less expensive. But overall, it works out better in terms of the power you get, the mileage you get, and the price at the pump. In other words, you pay around the same as you would for a small compact gasoline car, but you get the engine-power of a mid- to high-end sedan.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yo mama is so fat that when she went to a Star Wars convention in a "Slave Leia" costume, she won the price for best Jabba the Hutt costume.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

You should just use the initialization list instead:

Screen::Screen(pos ht, pos wd) :
  cursor(0), height(ht), width(wd),
  contents(ht*wd, ' ')
{ }

Screen::Screen(char c, pos ht, pos wd) :
  cursor(0), height(ht), width(wd),
  contents(ht*wd, c) 
{ }

// and default constructor (not required, but useful in general):
Screen::Screen() :
  cursor(0), height(0), width(0),
  contents() 
{ }

The initialization list is basically just a list of constructor calls for each data member. It is preferrable to put them in the same order as they appear in the class declaration, since that is the actual order in which they are constructed (and most compilers will warn you about that if you don't put them in the same order). Unless you have some complicated code to run in the constructor, you should prefer initializing the data members in the initialization list instead of the body of the constructor.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Thanks for posting that assembly code Schol-R-LEA, it is actually very interesting to look at the assembly code for the initialization section:

    leaq    _ZGVZ15get_first_valueiE1x(%rip), %rax
    movzbl  (%rax), %eax
    testb   %al, %al
    jne .L2
    leaq    _ZGVZ15get_first_valueiE1x(%rip), %rcx
    call    __cxa_guard_acquire
    testl   %eax, %eax
    setne   %al
    testb   %al, %al
    je  .L2
    movl    16(%rbp), %eax
    movl    %eax, _ZZ15get_first_valueiE1x(%rip)
    leaq    _ZGVZ15get_first_valueiE1x(%rip), %rcx
    call    __cxa_guard_release
.L2:
    movl    _ZZ15get_first_valueiE1x(%rip), %eax
    addq    $32, %rsp
    popq    %rbp
    ret

I know that this looks like gibberish to the average guy, but with only minimal knowledge of assembly, one can see that this is a double-checked locking initialization.

GCC created a guard, accessed through _ZGVZ15get_first_valueiE1x, to indicate whether the variable has been initialized already or not. Then, it created variable itself, accessed through _ZZ15get_first_valueiE1x. The code, is, in fact, derived from this canonical implementation (used by GCC and LLVM, and probably others, since this is the best way to implement a standard-compliant initialization of block-scope static variables):

if ( obj_guard.first_byte == 0 ) {
  if ( __cxa_guard_acquire(&obj_guard) ) {
    try {
      ... initialize the object ...;
    } 
    catch (...) {
      __cxa_guard_abort(&obj_guard);
      throw;
    }
    ... queue object destructor with __cxa_atexit() ...;
    __cxa_guard_release(&obj_guard);
  }
}

Which, in this case is:

static int x;
static /*unknown type*/ x_guard;

if ( x_guard.first_byte == 0 ) {
  if ( __cxa_guard_acquire(&x_guard) ) {
    try {
      x = value;
    } 
    catch (...) {
      __cxa_guard_abort(&x_guard);
      throw;
    }
    __cxa_atexit(/*destroy 'x' function*/);
    __cxa_guard_release(&x_guard);
  }
}

And because x is an integer, it does not …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you don't have a question and this is just a code snippet, then just say so, I'd be happy to turn the post into a code snippet.

About the code though, the one thing that really caught my eye was this statement that:

"Note: it is not advisable to use array in binary search tree because it consumes a lot of memory in the long run instead use linked list this is just a reference to understand more about BST."

Well, it is true that this kind of breadth-first layout in an array will require keeping a larger array then absolutely necessary. This is especially true in your implementation because you are not doing any tree-balancing. If there is anything that makes your code unusable in practice, it is the fact that your BST is not being dynamically re-balanced, and this is true regardless of the underlying storage (linked-structure or a contiguous array layout).

However, with a properly balanced tree, storing the values in a contiguous array layout is actually not that bad in terms of memory usage, as it uses, on average, about 50% too much memory. And if your elements are small, this can be much less memory overhead than what a linked-structure requires (for link pointers). Not to mention that most contiguous array implementations, like the classic Dynamic Array, will use an exponential growth strategy that results in a similar kind of memory overhead.

Finally, the main benefit of using a contiguous …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Ok, to settle this, let's just look at what the C++ standard says. Here is the relevant section (that I already quoted in another recent thread where the properties of those variables is a critical part of the design) about block-scope variables (i.e., local variables) with static storage duration. Section 6.7/4:

The zero-initialization (8.5) of all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed before any other initialization takes place. Constant initialization (3.6.2) of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope (3.6.2). Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

The translation into plain English is that if the variable has a trivial constructor (i.e. a POD …

deceptikon commented: For quoting the standard. :) +13
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Well, I have to correct the correction because what AD said is wrong. Local variables (defined in a function) with static storage duration (with static keyword) are created and initialized the first time control flows over that code (i.e., the first time the function is called). MandrewP was entirely correct. The C++ standard is 100% clear on this issue, and I don't know of any compiler that does not apply this correctly.

For example, this code is perfectly correct:

int get_first_value(int value) {
  static int x = value;
  return x;
};

int main() {
  std::cout << get_first_value(42) << std::endl;
  std::cout << get_first_value(69) << std::endl;
};

And it prints out 42 and 42, as expected. And, of course, the above code would be impossible if local static variables were "just like all other global variables".

Of course, if the type is just an integer (not a class with a non-trivial constructor) and the value it's initialized with is a compile-time constant, then that would allow the compiler to optimize this code by making it a statically-initialized static-duration variable, i.e., a normal global variable. In that sense, in this particular example, what AD said is probably true in practice, but it's an "as if" optimization case (i.e., it can be made into a global variable while looking "as if" it was a local static variable).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I just marked it as solved.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Here is a basic function object:

struct greater_than {
  bool operator()(int a, int b) const {
    return a > b;
  };
};

and the sort call just becomes:

sort(v.begin(), v.end(), greater_than());

where greater_than() just creates the function object that is passed to the sort function.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

First, if this is a C problem, you should have posted it in the C forum. So, please tell us if it is, in which case, it can be moved to the appropriate forum.

Second, we don't just solve people's assignments / exercises for them. You have to show that you are making efforts to solve the problem. What have you tried? What are the specific problem(s) you encountered?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

No, I think you would do well to just put the "OOPL" term out of your vocabulary. It's largely a meaningless term, IMHO.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

For pre-C++11 compilers, i.e. C++03 compilers, you should use the Boost libraries, which is where all the standard library additions came from, and will likely come from in the future. In this case, the Boost.Thread library is what you are looking for.

However, I doubt that your idea is really the best way to achieve what you want. To me, it sounds like the appropriate solution is the "futures and promises" method. See the boost::future documentation for example. The idea is pretty simple, you create a "promise" and an associated "future" (expectation of a value being delivered). The thread takes the "promise" and is responsible for fulfilling it at some point (i.e., giving it a value). The "main" thread keeps the "future" and can either wait for it to be fulfilled or regularly check it. The reason for this separation has to do with avoiding locks, probably in a similar way as you were thinking of using atomics.

By the way, standard atomics only work for trivially copyable types.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

As deceptikon says, object-oriented programming has a very plastic definition. Whenever an "OOP" language incorporates a clever feature, some start calling it a fundamental part of the paradigm, to the exclusion of any language that doesn't incorporate the same feature, or not to the same extent or ease of use.

In some sense, there's a Borg-like assimilation effect at play. Holding OOP on a pedistal often implies that any other "clever" programming pattern or technique must be somehow made a part of OOP, both to reinforce the glory of OOP, and to deny that there are clever non-OOP solutions to certain problems.

If you precisely define OOP as a certain set of mechanisms (e.g., run-time polymorphism) and certain design patterns, then you have to live with the fact that it will only be an appropriate paradigm to use in some situations, but not all. Some people can't live with that idea. I've met some of them, you can see, in their body language, the strong physical discomfort when you demonstrate to them a good programming technique that does not draw anything from OOP or follow any of its doctrines.

At the end of the day, programming paradigms are just about the way you understand the code. And describing "the way you understand the code" is difficult to do in concrete terms. It's often difficult to describe it in UML diagrams too, due to their limited descriptive power.

I don't think it is useful to use the term OOP to mean …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yo mama is so fat, that the GPS calculations have to be corrected for the gravity field she generates.

cproger commented: haha +0
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Sorry, you're not allowed to do that. Try begging Dani for permission or participating more in the community to gain additional privileges.

This site has a few restrictions for completely new members. These are designed to prevent spam and spam-bots. As any other popular forum site, spam is a recurring issue. There have been a number of specific spamming strategies that required some of the restrictions. For example, at one point, some spammers would create an account and start spamming and phishing all the other members with a massive "private messages" campaign, so the privilege to send PMs is now granted after 5 posts (or 10, I'm not sure). That solved it.

So, that's the explanation. Once you have made 5 (or 10) posts, you get all the same "privileges" as any other member (except mods and admins, of course).

which moron has developed your website and page?

That would be mostly Dani herself. And "moron" couldn't be further from the truth when it comes to describing Dani.

it has dropped in rank cause of such foolish response

No, the drop in ranking is mostly due to Google's many recent updates to their search engine. Read more about it here, here, and here.

2.13MB lol maybe you should really beg for a better page developer.

I don't understand. Is 2.13MB really that much? And is 0.029 seconds really that long? I'm not a web developer or …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I have never needed a car (living abroad and/or in a big city), except for borrowing or renting on occasions.

The closest I got to owning a car was having custody, for one summer, of my brother's 1973 Toyota Celica, one of only three that were still in driving condition at that time in all of Canada. That was an interesting car to drive, and especially cool to have around that time (summer after high-school). It made lots of noise and back-fires, often broke down, had a truck-style shift-stick, would only have enough power to turn on the radio when hitting the gas, and had a built-in "feet warmer", i.e., holes in the floor (under the dash) would let all the engine heat into the cabin. Oh, and let's not forget, it's quite an interesting / scary experience to drive a rear-wheel drive car in the Canadian winter, even with a trunk full of sand bags. My brother eventually drove all the way to BC (across the country, about 4,000 km) with it, but it didn't survive very long after that. :(

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

When people say that C++ isn't a real OOPL, they mean one of two things:

(1) C++'s implementation of OOP mechanisms (inheritance, virtual functions, etc..) is not "pure" OOP, or not pure enough.

(2) C++ is a multi-paradigm language, and OOP just happens to be one of the main paradigms that it directly supports, but not the only one.

I fall in the second category, as most experienced C++ programmers do.

And I despise people who fall in the first category, we call them "OOP zealots". It's true that C++'s implementation of OOP does not fall perfectly in line with the rigid dogmatic definition of OOP (or how an OOPL should work), but any reasonable person would say that it's "close enough", and would probably also say "who cares?". And if I'm gonna be frank, people who attack C++ as not being a "true" OOPL are often just making pity "grasping at straws" arguments against C++, a language they love to hate. Don't listen to those fools.

In my perspective, OOP was the awesome new way to program back in the late 80s and early 90s. Some still see it that way, but they just haven't kept up with the times. Modern C++ code makes very limited use of classic OOP style. Yes, OOP is "classic", not new or modern. I remember, when I first learned to program, in the late 90s, OOP was already the classic programming style.

A big part of this issue has to do with the …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster
Introduction

A recurring problem many newcomers face when tackling C++ is the compilation process, from sources to binaries. This tutorial will detail that process. It will be especially useful for people only familiar with higher-level languages (if any), but veterans of one or more native languages (C, Fortran, C++, D, etc.) might still learn a thing or two. And to that point, I would also mention that conceptually, most of this tutorial applies to any native, compiled language.

For widest applicability, this tutorial will feature GNU tools (GCC) used in a Unix-like environment (POSIX). For Mac OSX, the preferred compiler is Clang++, which involves a tool-suite compatible with GNU tools. Similarly, under Windows, the MinGW tools (incl. GCC) are also mostly the same, with some special issues. The only drastically different environment is the Microsoft Visual C++ compiler (MSVC). The oddities of the MSVC stack is beyond the scope of this tutorial.

Glossary

Before we start, we have to explain a few of the terms we will encounter:

Header file: Contains C++ source code and they are mostly used to make declarations, i.e., they contain the stubs that tell the compiler about the "things" that exists (somewhere). Usual extensions: .hpp, .h, or .hxx.

Source file: Contains C++ source code and they are exclusively used for definitions, i.e., the actual implementation of the "things" that make up the program or library. Usual extensions: .cpp, .C, or .cxx (normally, .c is reserved for C source files, not C++).

Translation unit (TU): A …

DeanMSands3 commented: Bookmarked! +5
Labdabeta commented: Excellent, as usual! +6
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

I just realized that my solutions are not exception-safe. The problem is that I set the is_created bool to true before making sure the constructor has completed. This is the way the core part should be done:

if( !is_created.load() ) {
  p_inst = std::unique_ptr<Singleton>(new Singleton());
  is_created.store(true);
};

or, for the other version:

if( !is_created.load() ) {
  Singleton* result = instance_impl();
  is_created.store(true);
  return result;
};
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Current shared pattern is based on Double check locking . May be we can minimize such calls by caching the pointer that instance returns. For example

The locking will occur only the first time you call the instance() function, and possibly locking some concurrent calls. But after that, there won't be any locking, just a check. So, caching the pointer is really only to limit the redundant checks, or, more importantly, the memory fence.

I'm afraid some people might be a bit lost with all this partial code, so, just to put things straight, here is the current solution you are talking about:

// in the header file:

#include <mutex>
#include <memory>
#include <atomic>

class Singleton {
  public:
    static Singleton* instance();

    void method1();
    void method2();
    void method3();
    //...

  private:
    Singleton() { };

    // thread-sync vars:
    static std::unique_ptr<Singleton> p_inst;
    static std::atomic_bool is_created;
    static std::mutex creation_mutex;
};

// in the .cpp file:

// statically initialized global variables:
std::unique_ptr<Singleton> Singleton::p_inst = std::unique_ptr<Singleton>();
std::atomic_bool Singleton::is_created = std::atomic_bool(false);
std::mutex Singleton::creation_mutex = std::mutex();

// lazy-initialized Singleton object:
Singleton* Singleton::instance() {
  if( !is_created.load() ) {
    std::unique_lock lock_here(creation_mutex);
    if( !is_created.exchange(true) ) {
      p_inst = std::unique_ptr<Singleton>(new Singleton());
    };
  };
  return p_inst.get();
};

As far as I know, this is the only completely thread-safe way to perform the initialization of the Singleton object in the way that you described (double-checked lock, notice what the C++11 section says..).

Of course, the easiest and most robust way to do this in C++ is:

// in …
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The C++ standard says this at section 11.3/7:

Such a function is implicitly inline. A friend function defined in a class is in the (lexical) scope of the class in which it is defined. A friend function defined outside the class is not (3.4.1).

This means that you can call "access()" from within the class (e.g., in the function body of a member function of the class), but the function is not visible (lexical scope) from the outside.

To solve the problem, you have to, at least, declare the function outside the class. For example, like this:

#include <iostream>
#include <memory>

using namespace std;

void access();

class a
{
    int i;
public:
    void display ()
    {
      cout<<"Hello";
    }

    friend void access()
    {
      a x;
      x.i = 10;
      cout << x.i;
    }

    friend a operator --(a &x)
    {
      x.i = x.i-1;
      return x;
    }

};

int main()
{
  a obj;
  --obj;
  access();
  return 1;
}
mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yo mama is so fat she has to stop at weight stations when driving on the highway.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Thanks for your comment but it is not thread safe and Their (static variables)order of destruction and construction is not entirely specified in C++

You are wrong. It is thread-safe and the order of destruction is deterministic. Here are the relevant parts of the standard:

Here is what the standard says about thread-safety of local static objects (section 6.7/4):

a variable [with static duration] is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. (note: The implementation must not introduce any deadlock around execution of the initializer.)

So, the current standard (not the old one) does guarantee that the initialization of local static variables is thread-safe.

And for the order of destruction, that is found in section 3.6.3/1, an exerpt of which is this:

If the completion of the constructor or dynamic initialization of an object with static storage duration is sequenced before that of another, the completion of the destructor of the second is sequenced before the initiation of the destructor of the first. (note: This definition permits concurrent destruction.)

In short, the standard requires obedience to the general principle that "everything is …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Agilemind is correct, as always ;)

And, another big part of the cost of health-care is administrative efficiency and bargaining power. The solution to solve most of the health-care cost issues is to find an insurer which is both efficient and has strong bargaining power... well, I guess we all know who that is: Medicare.

I'm referring, in part, to Steven Brill's brilliant piece in Time magazine which more or less reaches the undeniable conclusion that the best way to save costs to provide health-care is to lower the age of admissibility to Medicare, if not, make it an option for all, the so-called "Buy into Medicare" option that many people want, including a majority of Americans (about three quarters of Americans).

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

why the print is 5001 instead 5000?

Because there is a 1ms error. That's expected, your platform's timer has a resolution of 1ms.

can you give me a nice link for study about chrono libary?

You can navigate the main reference site, there are many examples under each different classes and functions.

Then, you can look at the Boost.Chrono documentation. That's because Boost.Chrono was the basis for the standard chrono library, so, most of the documentation is valid for both libraries.

why i didn't recive the mail when someone answer me?

I believe there is a slight delay. I think you are just faster then the system.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Moschops is correct, you are "protecting" the wrong part of the code. What could be subject to a race condition is the decision about whether to create the Singleton object or not. The creation of the object itself is not the problem. This would seem to suggest that the correct code would be this:

        pthread_mutex_lock(&mutex);
        if (m_pOnlyOneInstance == NULL)
        {
         m_pOnlyOneInstance = new MySingleton();
        }
        pthread_mutex_unlock(&mutex);

However, there are still causes for concern here, because both the "mutex" object and the m_pOnlyOneInstance pointer need to be initialized some time before this function is called, and if you want to implement the same "contruct-on-first-use" idiom for them, you will have the same race condition problem upon the creation of the mutex object. In fact, any construct-of-first-use global object (Singleton or not) will have this problem. You see how there is no "way out", which is probably why your professor gave this assignment, to teach you about the endless struggle when trying to create thread-safe code.

For the mutex, this is "simple" to solve. In general, any mutex pertaining to a set of threads must be created before the threads are started / created. This avoids all the synchronization issues. So, assuming that the mutex has already been created before starting any thread, then, it should be "safe". The same goes for the initialization of the m_pOnlyOneInstance pointer to NULL. So, to really talk about "thread-safe" implementation, you need to show that the creation of the mutex and the …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

what is the chrono type for use these big number?

That is none of your concern, nor is it mine. Chrono (like even the old time libraries) is designed to hide away all this nonesense about what type is actually used under-the-hood to store the time values. I don't know, and I don't care, and neither should you.

The kind of conversions that you are trying to do is already provided by the chrono library, and you should not attempt to do them yourself (in part, because of the possibly large numbers involved).

First of all, the chrono library has a number of "duration" times to represent various units, and they all inter-operate very well. And if you need to do a conversion, you can use the duration_cast function. So, your loop that tries to wait 5 seconds can be written like this:

#include <iostream>
#include <chrono>

using namespace std;

int main()
{
    auto start = chrono::high_resolution_clock::now();
    auto end = chrono::high_resolution_clock::now();
    auto interval = chrono::seconds(5);

    while ((end - start) <= interval)
    {
        end = chrono::high_resolution_clock::now();
    }

    // here is the part where I do a cast:
    auto total_ms = chrono::duration_cast< chrono::milliseconds >(end - start);
    cout << "The time elapsed was " << total_ms.count() << " ms." << endl;

    cin.get();
}

The chrono library uses a number of different types under-the-hood, but mainly you should know that some are time-points (time_point) and some are durations (duration). Their internal representations and whatever else is none of your concern, …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Yo mama is so fat that your dad has to make base-camp for the night when he climbs up on her.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Roll out a new health-care program that will allow millions of Americans to get insurance, possibly saving their lives. Yeah.. the server is going to get overwhelmed. Why is anyone surprised?

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

Digging a bit deeper, it seems that the reliability of QueryPerformanceCounter or the Linux equivalent isn't really much of a problem anymore. The whole issue had to do with multi-cores keeping separate counters and the introduction of cores that can slow down, thus, slowing the progress of the counters. Both Intel and AMD processors have had counter-measures (constant_tsc and hpet / lapic interrupts for sync'ing) for almost a decade now. So, there is really only a small window of PCs that have those features (multi-core / variable-speed) and that are, at the same time, too old to have the counter-measures. It seems like only "fancy" PCs from 2001-2005 or so might be susceptible to this problem (the list is short). I think it's one of these issues that has a life of its own, it was a short-lived concern at one point, but isn't anymore. It was only an issue with pre-Vista Windows high-end PCs from the early 2000s.

As I said earlier, you shouldn't expect the QueryPerformanceCounter or Linux equivalent to be reliable down to the "advertised" resolution of 1 nano-second. But, today, it's perfectly reasonable to expect reliability down to 1 micro-second or so. That is, unless you run a deprecated operating system (pre-Vista Windows) on a deprecated machine (about 10 years old).

sorry.. i'm confuse... so 1 000 000 it's 1ms?

Yes, it is:

1 milli-second (ms)  = 1,000 micro-seconds (us)  = 1,000,000 nano-seconds (ns)

And the scale of the high_resolution_clock durations is …

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

The scale is in nano-seconds. So, this means that your clock's resolution 1 millisecond (or 1 million nano-seconds). That's not great, but it will be just enough for you.

I'm guess that you are using Windows, and that your implementation / compiler does not yet support a "real" high-resolution clock, so it just uses the system clock, which has a resolution of 1ms on many modern versions Windows.

mike_2000_17 2,669 21st Century Viking Team Colleague Featured Poster

If you want to play youtube videos in the browser, you need to install flash-plugin.

To download youtube videos, you can use the youtube-dl program. As so:

$ sudo yum install youtube-dl

which is a command-line program to download youtube videos. See docs here.