C++ Will the C/C++ compiler optimize this if statement?

I have code like this, and I find it a bit hard to read: // code1 if( (expensiveOperation1() && otherOperation() && foo()) || (expensiveOperation2() && bar() && baz()) { // do something } I just changed it to the following, to make it more readable: // code2 const bool expr1 = expensiveOperation1() && otherOperation() && foo(); const bool expr2 = expensiveOperation2() && bar() && baz(); if(expr1 || expr2){ // one of t

C++ How does one include TR1?

Different compilers seem to have different ideas about TR1. G++ only seems to accept includes of the type: #include <tr1/unordered_map> #include <tr1/memory> ... While Microsofts compiler only accept: #include <unordered_map> #include <memory> ... As for as I understand TR1, the Microsoft way is the correct one. Is there a way to get G++ to accept the second version? How does one in general handle TR1 in a portable way?

C++ How do I wrap CFtpFileFind example, in C++?

Trying to wrap this short example in C++. (and its been a while since I did this). int main(int argc, char* argv[]) { //Objects CFtpConnection* pConnect = NULL; //A pointer to a CFtpConnection object ftpClient UploadExe; //ftpClient object pConnect = UploadExe.Connect(); UploadExe.GetFiles(pConnect); system("PAUSE"); return 0; } .h - class ftpClient { public: ftpClient(); CFtpConnection* Connect(); void GetFiles(C

C++ While using #ifndef, .h file being added multiple times

I am trying to use following pattern. #ifndef TRACER_H #include "Tracer.h" #endif This is statement is added to each file in the code such that tracer.h is added only once. Still I am getting an error saying multiple objects. Also Tracer.h contains #ifndef TRACER_H #define TRACER_H Here is the error; i tried pragma once as well: 1>Generating Code... 1>Linking... 1>LINK : \\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Debug\Project3.exe not found or not buil

C++ Why can I access private variables in the copy constructor?

I have learned that I can never access a private variable, only with a get-function in the class. But then why can I access it in the copy constructor? Example: Field::Field(const Field& f) { pFirst = new T[f.capacity()]; pLast = pFirst + (f.pLast - f.pFirst); pEnd = pFirst + (f.pEnd - f.pFirst); std::copy(f.pFirst, f.pLast, pFirst); } My declaration: private: T *pFirst,*pLast,*pEnd;

C++ Dangling reference. Alternatives for dangling pointers and references?

The following code produces dangling references: int main() { int *myArray = new int[2]{ 100, 200 }; int &ref = myArray[0]; delete[] myArray; cout << ref; // Use of dangling reference. } I know I shouldn't delete the array but in a large program what if somebody deletes memory to which I have a reference? Can it be somehow assured that no one deletes the array? What is the best strategy against dangling references and dangling pointers?

C++ private constructor

Possible Duplicate: What is the use of making constructor private in a class? Where do we need private constructor? How can we instantiate a class having private constructor?

C++ C++ Templates Issue

For the following code: #include <map> #include <iostream> #include <string> using namespace std; template <class T> class Foo{ public: map<int, T> reg; map<int, T>::iterator itr; void add(T str, int num) { reg[num] = str; } void print() { for(itr = reg.begin(); itr != reg.end(); itr++) { cout << itr->first << " has a relationship with: "; cout << itr->second << endl; }

C++ MFC Toolbar on Dialog?

I have tried everything I can think of to get a toolbar to show up on my dialog... including trying to create it myself with CreateWindow.. but it won't show up I created a dialog in the resource editor, and then made a class for it(tried deriving from both CDialog and CDialogEx). Isn't it possible to add a CToolbar control to it?

C++ Why does std::vector transfer its constness to the contained objects?

A const int * and an int *const are very different. Similarly with const std::auto_ptr<int> vs. std::auto_ptr<const int>. However, there appears to be no such distinction with const std::vector<int> vs. std::vector<const int> (actually I'm not sure the second is even allowed). Why is this? Sometimes I have a function which I want to pass a reference to a vector. The function shouldn't modify the vector itself (eg. no push_back()), but it wants to modify each of the conta

C++ Char* not retaining text inside my class - initialization constructor problem?

I have the following class (I've trimmed irrelevant stuff): class Example { private: char* name; int value[4]; int numVals; public: Example(); Example(char name[], int numVals, int, int, int, int); ~Example(); }; And here is the initialization constructor: Example::Example(char na[], int vals, int v1, int v2, int v3, int v4) { name = new char[strlen(na)+1]; strcpy(name, na); numVals = vals; value[0] = v1; value[1] =

C++ Output the type of a typedef at compile time in C++ (specifically when an error occurs)

It is very difficult for me to explain this particular problem/question so please bear with me (I am having trouble with all my template related questions!). Take this code as an example (note that the point of showing the code is to show a complex template hierarchy, not whether it makes sense): #include <string> #include <vector> #include <list> template <typename T> struct Foo { typedef typename T::value_type value_type; typedef typename T::value_type1 value_typ

C++ What can reset cursor shape apart from SetCursor?

I maintain a C++ application that uses flash ocx to play SWF file. When user hovers on button in SWF, flash internally makes a call to WinAPI SetCursor function to set IDC_HAND cursor - I can see that when I monitor WinAPI calls to cursor-related function via API Monitor V2 (rohitab.com). However, in my case the cursor is not changing, i.e. stays IDC_ARROW. The application itself does not call SetCursor at all. The window of the application processes WM_SETCURSOR message as following, i.e. doe

C++ Tracking visited nodes in a graph visitor

I have a graph which I traverse using a typical visitor pattern. I've run into an issue where I need to know if the node being visited has already been visited during the current traversal. I've developed a solution that I think would work, but it would require creating and destroying node "flags" during/after the graph traversal. That is, as each node is visited, a flag object pointer member in the node would be checked. If it's NULL, the visitor would create a flag object and assign it

C++ How does copy constructor work?

How does a copy constructor work in c++ Error 1 error C2064: term does not evaluate to a function taking 1 arguments c:\users\thuan\dropbox\homework\css 342\lab2\lab2\lab2\lab2.cpp 26 #include "intset.h" int main() { IntSet object1; IntSet object2(9); object1(object2); //error here return 0; } //constructor IntSet::IntSet(int a, int b, int c, int d, int e) { numOfArray++; int tempArray[] = {a, b, c, d, e}; size = determineHighest(tempArray) + 1; arrayPtr = new bool[size](); f

C++ How to overlay images using OpenCv?

How can I overlay two images? Essentially I have a background with no alpha channel and than one or more images that have alpha channel that need to be overlaid on top of each other. I have tried the following code but the overlay result is horrible: // create our out image Mat merged (info.width, info.height, CV_8UC4); // get layers Mat layer1Image = imread(layer1Path); Mat layer2Image = imread(layer2Path); addWeighted(layer1Image, 0.5, layer2Image, 0.5, 0.0, merged); I also tried using m

C++ Get values from XML <tag> in C++ using libxml2

I am having a hard time to get the values from a XML file. We are using libxml2 and python (output to *.txt) and then C++ to read the *.txt file. I would like to use libxml2 in C++ without going through Python. My problem is the reader (see example below). BTW: I do not get much from this example code from http://xmlsoft.org/examples/index.html#reader1.c Could someone tell me how i get the value = xmlTextReaderConstValue(reader); into a string? In summary: Loop through XMLdoc {if "XML-tag-"

C++ Member from base class template not found

Possible Duplicate: Why do I have to access template base class members through the this pointer? I have a class hierarchy like the following: template<typename T> class Base { protected: T t; }; template<typename T> class Derived: public Base<T> { public: T get() { return t; } }; int main() { Derived<int> d; d.get(); } The problem is that the protected member variable t is not found in the Base class. Compiler output: prog.cpp: In member fun

C++ Set upper and lower bytes of an (short int) in C++

i have problem for setting upper and lower bytes of (short int). please look on my code it just return number 1 but must return 55 . int number = 55; int mynumber = 0; //convert short int to char. char upper = number >> 8; char lower = number && 8; //convert char to short int . mynumber = (mynumber & 0xff00) | lower; mynumber = (mynumber & 0x00ff) | (upper << 8); printf("%i",mynumber);

C++ HRESULT "Class Not Registered" Implementing simple COM server DLL

I'm following this sites tutorial: http://progtutorials.tripod.com/COM.htm Preliminary evidence: Visual Studio 2010, Windows 7 64 bit. and I'm coding the examples in section 3. (Implementing a server DLL). I've typed out the code exactly as shown and I'm getting a "Class not registered" exception when executing this code on line 12 of the code outlined in section 4.1 (where the tutorial shows you how to access the DLL and I have followed 3.1 to the letter): hresult hr = CoGetClassObject(CL

C++ Function variable instead of pointer to function

There is this code: void a() { } // function parameter first defined as function, then as pointer to function void g(void f() = a, void (*d)() = a) { } int main(){ void (*z)() = a; // works ok //void z() = a; error: illegal initializer (only variables can be initialized) return 0; } In function parameter list you can define function parameter as a function or as pointer to function (see function g parameter list). However in main function only pointer to function version seems to w

C++ Why can't I find <QTcpServer>?

My VS2010 can only #include <Qt/qtcpserver.h> but can't #include <QTcpServer>. Qt assistant suggested <QTcpServer> be included to apply TCP server but it seems this header cannot be found by my VS2010, but it can find <Qt/qtcpserver.h> and these two headers seems to be the same. Are they the same and why can't I find <QTcpServer> ? PS: I'm currently using Qt4 plugin with VS2010. Here's a snapshot of my VS project files: No .pro file there.

C++ safely terminating a thread in Meyers Singleton

I have a boost thread running inside a Meyers' Singleton. It happily runs for the duration of my program. When my Singleton's destructor is called (when the program is loaded out of memory) I set a flag so that the thread should exit it's loop and fire off a call to thread.join(). Now, on Windows, calling thread.join() causes a bad access exception. But on Mac, not calling thread.join() throws a bad access exception! Can anyone shed any light on this difference in behaviour between these 2 o

C++ If statements in c++ doubles

i cant see the get the initial if statement to work no matter what number i type in it would auto display the out of number range. also am i allowed to place the conditions like that soo close like if (x < 0)(x > 100);. also how do i make it soo it returns to the start of the program?

C++ What is the safest way to convert long integer into array of chars

Right now I have this code: uint64_t buffer = 0; const uint8_t * data = reinterpret_cast<uint8_t*>(&buffer); And this works, but it seems risky due to the hanging pointer (and looks ugly too). I don't want naked pointers sitting around. I want to do something like this: uint64_t buffer = 0; const std::array<uint8_t, 8> data = partition_me_softly(buffer); Is there and c++11 style construct that allows for me to get this into a safe container, preferable a std::array out of a

C++ Linear movement stutter

I have created simple, frame independent, variable time step, linear movement in Direct3D9 using ID3DXSprite. Most users cant notice it, but on some (including mine) computers it happens often and sometimes it stutters a lot. Stuttering occurs with VSync enabled and disabled. I figured out that same happens in OpenGL renderer. Its not floating point problem. Seems like problem only exist in AERO Transparent Glass windowed mode (fine or at least much less noticeable in fullscreen, borderles

C++ Does Boost.Serialization Free the Memory Created during Loading Pointers?

To be specific, I'm referring to the demo in Boost.Serialization tutorial here. In the above demo, bus_top instances are stored as pointers in bus_route to showcase how serialization of pointers is achieved. However, I observed an interesting behavior, that is, the destructor bus_stop::~bus_stop() is never invoked for the bus_stop objects created by restore_schedule(). I put a break point in bus_stop::~bus_stop() and it was triggered only by the delete statements at the end of main function. D

C++ Smart pointers memory managers in Qt

I'm trying to develop a Qt Application for mobile phones, so I decided not to use any standard library(as I fear some platform may not yet be supported). So, I had to reimplement the smart pointer wrapper(using the standard draft, of course) without any standard headers. In Qt, there are some Widgets, such as QMenu and QToolBar which when needed to be created -- It is created as such QMenu *mainMenu = new QMenu; QToolBar *toolBar = new QToolBar; //To add a new menu bar or ToolBar, we do mainMen

C++ How can I insert the content of arrays into a vector?

I need to write some simple code with std::vectors and I am struggling a bit. I have a char[] buffer that is filled with callback data from another program. I need to append this data to the end of a vector - the whole buffer. std::vector<char> vector; // data comes from another program void callback(char buffer[], size_t size) { // copy buffer to the end of vector here } At the end the vector is supposed to contain continuous data from the buffer. Is there an effective way to do

C++ Static *template* class member across dynamic library

Edit: the comments below the accepted answer show that it might be an issue with the Android dynamic loader. I have a header for a template class with a static member. At runtime the address of the static member is used in the library and in the client code. The template is implicitly instantiated both in the library and in the client code. It works fine on Linux and OSX, the symbol is duplicated but marked as "uniqued" as shown by nm (see below). However when I compile for ARM (Android), the s

C++ cocos2d-x label text char spacing

I use cocos2d:::Label and I need to control the spacing of adjustment characters in the text. I use cocos2d-x 3.0 and the font of the label is TTF. Is it possible to achieve, or I should use another thing instead of cocos2d:::Label?

C++ boost: time_facet milliseconds without dot

I need to create a timestamp with boost in the format: YYYYmmDDhhMMssFFFF (with F = Milliseconds). I use facet->format("%Y%m%d%H%M%S%F"); but the output includes always a dot between seconds and milliseconds. This is the output: "20150202140830.779716" Is there a better way to achieve my format than to replace the dot and cut the last two digits by hand?

C++ Best way to check if double equals negative infinity in C++

I found this: http://en.cppreference.com/w/cpp/numeric/math/isinf but it appears to check for either positive or negative infinity. I just want to check if a value is equal to exactly negative infinity, or in otherwords is log(0) Thanks for answer! Based on response below, here is some code that shows what works. #include <iostream> #include <cmath> #include <math.h> using namespace std; int main() { double c = std::log(0.0); auto result = c == - INFINITY; cout &

C++ How do stackless coroutines differ from stackful coroutines?

Background: I'm asking this because I currently have an application with many (hundreds to thousands) of threads. Most of those threads are idle a great portion of the time, waiting on work items to be placed in a queue. When a work item comes available, it is then processed by calling some arbitrarily-complex existing code. On some operating system configurations, the application bumps up against kernel parameters governing the maximum number of user processes, so I'd like to experiment with m

C++ Why do c++ libraries often define their own primitive types?

I have started using OpenCL library lately and I've noticed that they are using their own integer types, like cl_int and cl_uint instead of int and unsigned int. Why is that? Why don't they use the types that are by default in the language? Is it a good practice or are there practical reasons for this (i.e. more readable code)?

C++ Definition and Declaration of derived classes in *.h file and *.cpp file

I'm having some slight problems with the declaration of a derived Constructor in a header file and its definition in a *.cpp file my header file: class Nrpeoutputquery : public Query { private: std::string queryText; std::string queryType; public: //default Constructor Nrpeoutputquery(); //Constructor Nrpeoutputquery(std::string queryText, std::string queryType, sql::Connection *connection) : Query(connection); //Destructor ~Nrpeoutputquery(); }; my *.cpp fi

C++ error: 'sort' is not a member of 'std'

I just would like to ask what does this error mean and how to fix it thanks! error: 'sort' is not a member of 'std' vector<int> result; for (auto & i : numbers) result.push_back(std::stoi(i)); std::sort(result.begin(), result.end());

C++ Handling Division by Zero Error

So I posted code awhile back and the code runs fine. The code performs Addition, Subtraction and Multiplication to the two fractions then it finds out if the first fraction is smaller than the 2nd fraction, and lastly on the 2nd line it calculates the decimal form of the fraction. But I need to throw an exception that if the denominator is ever 0 the constructor will stop and throw an "Invalid Input" message, and then continues to the next set of inputs. Input 2 2 0 4 5 1 2 3 4 Expected Out

C++ pragma warning( disable : 4700 ) not working in Visual Studio Express 2013

Compiling the following code in Release configuration with SDL checks disabled: #include <immintrin.h> int main() { const auto Set128Epi16 = []() { #ifdef NDEBUG #pragma warning( push ) #pragma warning( disable : 4700 ) __m128i x = _mm_cmpeq_epi16( x,x ); x = _mm_srli_epi16( x,15 ); return _mm_slli_epi16( x,7 ); #pragma warning( pop ) #else __m128i x = _mm_setzero_si128(); x = _mm_cmpeq_epi16( x,x ); x = _mm_

C++ Wrong results using trained caffe net from c++

I tried to use my trained caffe net with my data from C++. I implemented standard caffe example classification.cpp for deploy. In train/test phase with python scripts the net achieved accuracy = 0.93, but now when I went to deploy I got some strange results. I have two classes: environment object and I need to get the prob of object detection. I believed that the results will be presented in the form of two probs in Softmax output blob if the net have two outputs in FC-layer (prob1 + prob2 =

C++ Avoid an infinite loop while waiting for user input?

I'm caught in a logical catch-22. Let me clarify what I am trying to do: A button press will trigger a motor to move until a sensor is felt (sends 3.3V to my Rpi GPIO), at which point it will reverse direction. This all works fine; the problem is, it is stuck within an infinite loop, so if I want to press another button, for example to increase the speed, or stop it in the middle of a run, well, I can't. I have tried to implement "wiringPiISR()", as an interrupt, but that seems to also b

C++ Template class extending from non-template base class and overriding function parameters

I am trying to create a non-template base class for the PacketDecoder so I can store Base* in a std::map. The decode function is being overridden properly. The encode function is giving me this error "'encode' is not virtual and cannot be declared pure". I might be thinking about this problem wrong coming from a Java background. Is there a more idiomatic c++ approach to this problem? class Base { public: virtual Packet* decode(folly::io::Cursor& cursor) = 0; virtual void encode(Pack

C++ Can a QObject living in one thread emit a signal from another thread?

I have an object a created in the main thread, where its signals are connected to slots of another object, b, that also lives in the main thread. Then I create an object c and move it to a worker thread, where it will periodically access object a through a pointer, change its state and emit its signals. Here is the code: (Note: some lines were purposely ignored to keep the example short.) class A : public QObject { Q_OBJECT friend class C; signals: void sigA(); private: qu

C++ How to use references/pointers with mathematical operations in c++?

I'm pretty new to C++ pointers and references. Say I have two variables i1 and i2, is there a way I can track their difference (or any other operation), even if one of them changes. My attempt at this is shown below, as well as what I want to achieve. int i1 = 20; int i2 = 20; int*r1 = &i1; int*r2 = &i2; int s = *r1-*r2; std::cout << s << std::endl; i1 = 40; std::cout << s << std::endl; //OUTPUT //0 <- 20-20 //0 <- How do I make this 20, since 40-20 is 20

C++ Making (virtual) functions made innaccessible in intermediate base class accessible in most-derived class, well-defined?

Consider the following code: #include <iostream> struct a { virtual void f() = 0; }; struct b: a { private: void f() override { std::cout << "b::f()\n"; } }; struct c: b { public: using a::f; }; int main() { ::c c; c.f(); } This compiles and works as expected with g++, clang and msvc, i.e., print b::f(). However, if I replace a and b by this: struct a { void f() { } }; struct b: a { private: using a::f; }; ...the code does not compi

C++ What is difference between begin() and data()

begin() and data() both returns iterator pointing to the first element. But, the definition of data() says it Returns a direct pointer to the memory array used internally by the vector to store its owned elements. I can also use them to access any element. So, how both of them are different? consider the following example, #include <iostream> #include <vector> int main() { std::vector<int> v; v.reserve(5); for (int i = 1; i <= 5; i ++) v.push_back(i);

C++ How do I compile a c++ program into a 32-bit executable instead of 64-bit

So I am trying to compile a c++ program and have the executable be 32-bit instead of 64-bit. The system (using a program to simulate a system) I want to run it on is 32-bit and seeing as compiling the program yields 64-bit ELF files I cannot run them. I have added the -m32 flag to the makefile and when compiling i get the following errors: /usr/bin/ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/5/libstdc++.so when searching for -lstdc++ /usr/bin/ld: skipping incompatible /usr/lib/gcc/x8

C++ How to "fully bind" a constant buffer view to a descriptor range?

I am currently learning DirectX 12 and trying to get a demo application running. I am currently stuck at creating a pipeline state object using a root signature. I am using dxc to compile my vertex shader: ./dxc -T vs_6_3 -E main -Fo "basic.vert.dxi" -D DXIL "basic.vert" My shader looks like this: #pragma pack_matrix(row_major) struct VertexData { float4 Position : SV_POSITION; float4 Color : COLOR; }; struct VertexInput { float3 Position : POSITION; floa

  1    2   3   4   5   6  ... 下一页 最后一页 共 2840 页