question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,242,570 | 4,242,603 | What is the difference when I write Func1(int &a) and Func1(int *a)? |
Possible Duplicate:
Difference between pointer variable and reference variable in C++
As I am starting with C++, I found the operation below confusing. I got to know about passing by reference and passing by value. But recently I came across functions like this which confused me:
Func1(int &a)
Func2(int *a)
Both of... | Func1(int &a)
// It accepts arguments by reference.
// Changes to an inside Func1 are reflected in the caller.
// 'a' cannot bind to an Rvalue, e.g., it can't call Func1(5)
// 'a' can never be referring to something that is not a valid object
Func2(int *a)
// It accepts arguments by value.
// Change to an inside Func1... |
4,242,571 | 4,242,607 | my query produces error “ORA-00933: SQL command not properly ended” in C++ | Here is my query
csQuery.Format (_T ("INSERT INTO EFFECTS
(EFFECT_NM,EFFECT_VALUE_NUM,EFFECT_DIR_NM,PROJECT_ID_SQ)
SELECT '%s',%f,'%s',STACK_GAP.PROJECT_ID_SQ
where PROJECT.PROJECT_NM = '%s'"),TDName,TDvalue,TTDdirection,csProjectName);
I am getting SQL command not properly ended error ... | You need to put a semicolon after your INSERT query, I believe.
csQuery.Format (_T ("INSERT INTO EFFECTS(EFFECT_NM,EFFECT_VALUE_NUM,EFFECT_DIR_NM,PROJECT_ID_SQ) SELECT '%s',%f,'%s',STACK_GAP.PROJECT_ID_SQ where PROJECT.PROJECT_NM = '%s';"),TDName,TDvalue,TTDdirection,csProjectName);
|
4,242,692 | 4,242,709 | Warnings in a homework problem C++ | Getting two warning when i run this program and i can't figure out how to stop this from happening. Any help would be appreciated!
warning: comparison between signed and unsigned integer expressions
Is the warning I'm getting for 2 lines in the extract_word function.
#include<iostream>
#include<string>
using namespa... | You assign the result of a.find(" ") to a size_t. size_t is an unsigned type; it can never have a negative value.
Note that that does not mean the comparison will never be true. The -1 will be converted to be unsigned so the comparison can be performed (this is part of what are called the usual arithmetic conversions... |
4,242,773 | 4,242,801 | error C2819: type 'Robot::Animation' does not have an overloaded member 'operator ->' | I cannot for the heck of it find why this is throwing an error! Okay so I have a Struct that contains some objects. I then create a pointer to that struct and set the items one by one. By I keep getting an error. Here's the code:
Robot.h:
// Name and Animation info
std::map<std::string, Ogre::AnimationState*> mAnim... | I think your error is there:
// Set the animations name
mAnimation->name = Animation->mAnimState->getAnimationName();
That probably should be:
// Set the animations name
mAnimation->name = mAnimation->mAnimState->getAnimationName();
|
4,242,776 | 4,243,134 | How to monitor windows server 2003/2008 user logins? | I wanna write a program that should perform some tasks automatically if someone logs onto my server.
My questions regarding this are:
1) Is there a last login record that
is set right after a user logs in
that I can use/monitor for my
purpose? If not is there something
similar I can use?
2) What's the best way to cons... | Your best (and by far safest) bet is to create a service that accepts the SERVICE_CONTROL_SESSIONCHANGE control.
This will allow your service control handler to receive a control whenever a user logs on, logs off, locks the session, and various other options. Look for more info in a link blow.
This is done by creating ... |
4,242,879 | 4,244,202 | C++: Callbacks and system timer events during destructor cascade | Assume an OO design where objects call each other, and after a while the called upon objects callback the initiating objects (calls and callbacks). During normal program termination, while destructors are called, is there some kind of promise that no system timers will be called, and no object will initiate a callback?... | There is a pretty awesome library to handle these kinds of calls, and of course it's a Boost one.
Behold Boost.Signals2, with guarantees of correctness even in multi-threaded application :)
Note in particular the use of boost::trackable class, so that objects destruction automatically invalidate the calls before they h... |
4,242,910 | 4,242,919 | Accessing a class member variable by its name at runtime | In the vein of more impossible-but-is-it-really questions:
Is it possible to access the member variable of a class, where the variable's name is stored in a string?
class Test
{
public:
int test = 0;
}
string name = "test"; // let's assume we know test is an int.
Any chance of getting the value of test, using the stri... | No.
To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.
|
4,242,937 | 4,243,354 | class objects in c++ | i need to write a program in which main() would read a file(containing some predefined instructions) and create classes for each line and if a class object was already created, create a new class object.. something like
main()
{
read file;
save to a vector;
for(i < vectorsize; i++)
if(vector[... | You might use a std::map to store the created books. A map is a key->value store where you can adress the content by a own defined key.
typedef std::map<std::string, Book> BookMap;
int main()
{
read file;
save to a vector;
BookMap books;
for(i < vectorsize; i++)
if(vector[i]== "book")
... |
4,243,027 | 4,243,114 | winsock compiling error, it cant find the addrinfo structures and some relating functions | I've just started learning winsock through the "Beej's guide to network programming" book. I'm programming under windows and running it through gcc. This is just a start to writing my first server program but it gives me these errors when I try to compile.
/* Server */
#include <iostream>
#include <windows.h>
#include ... | You probably want to #include <ws2tcpip.h>. Remember that before Stack Overflow, Google is your friend for this kind of questions : you will get immediate answers from MSDN !
|
4,243,126 | 4,243,362 | Program crashes with 0xC000000D and no exceptions - how do I debug it? | I have a Visual C++ 9 Win32 application that uses a third-party library. When a function from that library is called with a certain set of parameters the program crashes with "exception code 0xC000000D".
I tried to attach Visual Studio debugger - no exceptions are thrown (neither C++ nor structured like access violatio... | That's STATUS_INVALID_PARAMETER, use WinDbg to track down who threw it (i.e. attach WinDbg, sxe eh then g.
|
4,243,160 | 4,243,168 | How to search for an element in a vector? | i have a code like this....
std::vector<string>::iterator p;
p = find(v.begin(),v.end(),"asdasda");
cout << *p << endl;
if "asdasda" is not a part of the vector, p points to some garbage and cout gives a seg fault. what should be the if statement that would make the cout execute onlyif "asdasda" was found?
and also... | p doesn't point to "garbage", it simply becomes v.end() when the content is not found.
if (p != v.end()) {
std::cout << "v[" << (p - v.begin()) << "] = ";
std::cout << *p << std::endl;
}
|
4,243,387 | 4,243,460 | Just installed Netbeans and the c++ plugin, but brand new main file already has a error | HI
I recently purchased a netbook for the purpose of being able to code whilst away from home, and everything is pretty dandy, I installed Kubuntu and then netbeans, as netbeans seems to be the better IDE available for linux. I installed the c++ plugin and started a new project, and the IDE is already giving a error:
#... | Did you install the C++ compiler and its headers as well? By default Ubuntu installs do not have g++ installed. The following command will install stuff essential for development in Ubuntu, like gcc, g++, and headers, and make.
sudo apt-get install build-essential
|
4,243,405 | 4,243,603 | How do I configure compiler warnings in Visual Studio 2010? | I recently started coding in C++ with Visual Studio 2010.
Now I am looking for an option to warn if a function has been declared, but not defined. That option would be found in the compiler options, wouldn't it? After a quick search on Google I found this: http://msdn.microsoft.com/en-us/library/c553zwz0.aspx which is ... | In that window expand 'Konfigurationseigenschaften', expand the child 'C/C++' and select 'Allgemein'. Now you can set the warning level (Warnstufe) to EnableAllWanings (/Wall).
Though I don't think the warning you are looking for exists, at least I couldn't produce it.
|
4,243,565 | 4,243,842 | Minimalistic destructors? | We have some issue with my friend. Assume, we have a class which implements database connection, like this:
class DB
{
void Connect();
void Disconnect();
// ...
~DB();
};
In my opinion, destructor should be minimalistic, which means destructor should not call Disconnect method when connection was established. I think,... | The RAII idioms says: acquire in the constructor and release in the deconstructor. You must guarantee that your deconstructor will NOT throw anything. Otherwise you will have core dump (or undefined behaviour) if your object deconstructor will throw an exception during the stack-unwind.
Also in your specific case I wil... |
4,243,880 | 4,243,905 | Substitute for forking in windows | I've been following Beej Networking guide and in the server section there is portion of code where it has called a function fork().
if (!fork()) { // this is the child process
close(sockfd); // child doesn't need the listener
if (send(new_fd, "Hello, world!", 13, 0) == -1)
perror... | fork() obviously doesn't exist on Windows. Instead you'll need to create a new thread, or a whole new process.
|
4,243,886 | 4,244,001 | Inserting binary data via QSQL | How to insert binary data to table "test" from "database" with 2 columns text "name" and bin "pic"
QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");
db.setUserName("user");
db.setPassword("pwd");
db.setPort(1234);
db.setDatabaseName("database");
| You can have a look at http://www.java2s.com/Code/Cpp/Qt/UsingsqldatabasefromQt.htm snippets
First you need to open the DB db.open();
One way would be
QSqlQuery query;
query.prepare("INSERT INTO test (name, pic) "
"VALUES (:name, :pic)");
query.bindValue(":name", "Bart");
query.bindValue(":pic", "Bart.jpg... |
4,243,915 | 4,243,950 | Casting between signed and unsigned | Is this safe:
int main()
{
boost::int16_t t1 = 50000; // overflow here.
boost::uint16_t t2 = (boost::uint16_t)t1;
std::cout << t1 << " " << t2 << std::endl;
}
To be even more specific: I'm storing this data in a table which is using signed types in its schema, is it safe to store, and retrieve this data ... | No, I believe this is implementation defined. From the C++ draft standard, §4.7/3
If the destination type is signed, the
value is unchanged if it can be
represented in the destination type
(and bit-field width); otherwise, the
value is implementation-defined.
This applies to the first statement. int16_t is si... |
4,243,972 | 4,244,008 | How to change my error handling method | I can't seem to get my head around why people say C++ exceptions are better. For example, I have an application which loads function objects from shared objects to be used in the application. What goes on is something like this:
bool LoadFunctions()
{
//Get Function factory.
FunctionFactory& oFactory = GetFunctio... | We don't even need return codes. If a problem occurs it should be in the exception.
int main()
{
try
{
LoadFunctions();
// if we're here, everything succeeded!
}
catch(std::exception _e)
{
// output exception message, quit gracefully
}
// IRRESPECTIVE OF SUCCESS/... |
4,244,016 | 4,244,093 | Why C-forkbombs don't work like bash ones? | If I run the classical bash forkbomb:
:(){ :&:&};:
my system hangs after a few seconds.
I tried to write a forkbomb in C, here is the code:
#include <unistd.h>
int main( )
{
while(1) {
fork();
}
return 0;
}
When I run it the system gets less responsive, but I can kill that process (even after min... | That C program is tiny, seriously tiny. In addition, fork()'ing a program like that is very, very efficient. An interpreter, such as Bash, however, is much more expensive in terms of RAM usage, and needs to access the disk all the time.
Try running it for much longer. :)
|
4,244,095 | 4,244,245 | System function seems to ignore quote marks | I'm running the following code (on Windows 7, if it makes a difference):
char temp[20000];
sprintf_s(temp, 20000, "\"C:\\Program Files\\Mozilla Firefox\\firefox.exe\" \"http://www.tvtak.com/servlet/Gateway/?C=addShows&channel=%s&show=%s\"", _channels[chId], name);
system(temp);
On running, the console displays:
'C:\P... | You are better off with CreateProcess() to avoid cmd.exe's quoting hell. But if you must use system() you can simply append if 1==1 to the beginning of your command so it doesn't remove the quotes for you.
system("if 1==1 \"C:\Program...");
For more information about this issue, run cmd.exe /? and look for /S.
|
4,244,274 | 4,244,297 | How do I count the number of zero bits in an integer? | How would i go about finding the number of 'zero' bits in C++.
Suppose I have an integer;
int value = 276;
For which I have the bits 100010100, but how do I count the zeros?
| The easiest most naive way is to just iterate over the bits and count:
size_t num_zeroes = 0;
for(size_t i = 0; i < CHAR_BIT * sizeof value; ++i)
{
if ((value & (1 << i)) == 0)
++num_zeroes;
}
There are all number of better (for different values of "better") ways, but this is quite clear, very terse (code-wise)... |
4,244,421 | 4,244,468 | Clarification on template function specialization | I want to create a calculator
template < typename T >
class Calculator
{
public :
Calculator ( void );
~Calculator ( void );
T add(T a, T b)
{
return ( a + b ) ;
}
};
Now I want to make this Caculator add strings, so add("Tim","Joe") shall give me "TimJoe" .
Can I use template function... | Why would you want to ?
Calculator<std::string> a;
std::cout << a.add("Hello", " world") << std::endl;
This code outputs "Hello world". It's not optimal (std::string parameters in the add member function are taken by value), but it does not require a specialization to work.
EDIT OK, you want specialization, but you ca... |
4,244,478 | 4,250,644 | How to catch if my camera resolution has not changed? | I want to try to set some exotic resolutions on my web-camera device. like 100x1000 or some standart. I need to find out if my camera supports desired resolution. Howto get such info using OpenCV? (because it seems to me that my try-catch around cvSetCaptureProperty does not work, while that function does not return an... | Is there a cvGetCaptureProperty? If so, what does it return after you set the resolution?
|
4,244,623 | 4,245,052 | How to take string length of a String array? | I have declared a string array String s;
I tried finding the length of the string by giving strlen(s) but it didnt work . How to get the length of the string ?
| The function strlen does not take a string, but an array of chars. Please see this reference for examples. If you are using the type string you will find it's length by using the function length(), like this:
std::string text = "Some text";
int length = text.length();
For more examples see this other question.
|
4,244,882 | 4,245,072 | Sendto() function giving errors . How to debug them? | /*
** talker.c -- a datagram "client" demo
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fstream>
#include <iostream>
#include <string>
... | First corrections to your code:
char* mess = malloc(20*sizeof(char));
sprintf(mess,s);
if ((numbytes = sendto(sockfd,mess, s.length(), 0, p->ai_addr, p->ai_addrlen)) == -1)
// ...
There's no need to dynamically allocated such a little buffer, whose size is predictable at compile-time.
s is a string object, not a... |
4,244,903 | 4,245,116 | Replace return with a tab for standard input | I was writing a program in C++ to input values for a NxN matrix. Generally, one would enter an integer and press the Return key for NxN times. But I would like to make the cursor move the length of a tab for every value entered by the user. This carries on for a row, and then a new line is prompted for inputs for the n... | The question is lacking code : what have you tried ? What is the problem ?
If you want to get into ncurses and don't know where to start, I'd recommend reading some tutorials : see this page and this page regarding keyboard interfacing. Feel free to come and ask more questions if you encounter issues once you have some... |
4,244,913 | 4,244,942 | How to read the attribute and element value | I have the following XML:
<?xml version="1.0" encoding="utf-8" ?>
<lastconnectedServers>
<Server ip="172.24.18.240" domain="MyDomain">
<SharedFolder name="MyShared" type="FTP"/>
<SharedFolder name="Share1" type ="CIFS"/>
<SharedFolder name="Share2" type ="both"/>
</Server>
</lastconnectedS... | A quick search through MSDN would have saved you a lot of time:
HRESULT getNamedItem(
BSTR name,
IXMLDOMNode **namedItem);
See: http://msdn.microsoft.com/en-us/library/ms767592(v=VS.85).aspx
|
4,244,953 | 4,245,165 | Function description | If I have fnc like this:
void fnc(const SomeType&){/**/}
And when I list preconditions and postconditions for this fnc I think that listing precondition of form:
SomeType must be of a correct type is rather dumb, isn't it? I'm asking for this because at my uni they want us to list something like this but if the type... | Don't state the obvious.
As you say, the code clearly won't compile if the types don't match up.
The pre- and post-conditions will depend on what the function is trying to do.
|
4,245,152 | 4,245,167 | Problem C++ STD Iterator comparison operators | Good day sirs,
because it looks like mine isn't going to be that good.
I have a class C, which doesn't have any children but has a vector made of pointers to instances of another class, let's call it B:
class C
{
public:
...
std::vector<B*> elements;
...
}
B also has a vector of pointers to in... | You should try this :
std::vector<B*>::iterator it1;
std::vector<A*>::iterator it2;
for (it1=this->elements.begin(); it1 != this->elements.end(); ++it1)
{
for (it2 = (*it1)->elements2.begin(); it2 != (*it1)->elements2.end(); ++it2)
{
(*it2)->do_something(); //method of class A
}
}
In the inner lo... |
4,245,281 | 4,247,683 | Strange problem with conversion | In code below:
template<class Key, class Value>
class Pair
{
private:
std::pair<Key,Value> body_;
public:
//No cpy ctor - this generated by compiler is OK
Pair(Key&& key,Value&& value)
{
body_.first = key;
body_.second = value;
}
... | return Pair<Key,Value>(std::forward<Key>(key),std::forward<Value>(value));
Although I'm not really sure why rvalue forwarding isn't implicit.
Edit: Oh, I guess I got it. This way you can still pass a rvalue reference to a function that takes value.
|
4,245,320 | 4,245,343 | Intercepting c++ exceptions | So my c++ program just crashed, and the error I got was:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
Aborted
Now, what I've added recently to my code is a SIGSEGV handler, so if it was a segmentation fault, it would proceed to print the stack trace.
How do I go... | Use set_terminate function which sets the terminate handler function:
A terminate handler function is a
function automatically called when the
exception handling process has to be
abandoned for some reason. This
happens when a handler cannot be found
for a thrown exception, or for some
other exceptional ci... |
4,245,644 | 4,245,717 | c++ / c# Problem in named pipe | This is my c++ code
HANDLE hPipe = ::CreateNamedPipe(_T("\\\\.\\pipe\\FirstPipe"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
PIPE_UNLIMITED_INSTANCES,
4096,
... | LPWSABUF is pointer, its size is 32 or 64 bit. Possibly you mean this:
WriteFile(hPipe, lpBuffers, sizeof(WSABUF), &bytesWritten, NULL);
|
4,245,673 | 4,246,085 | VB6/C++ WINAPI to C# | I'm working with some hardware which has a DLL. I believe it has two methods of calling the functionality (from using a DLL spy app).
It currently works in VB6 using
Public Type Versions
Pname As Long
Manuf As Long
VMajor As Long
VMinor As Long
VState As Long
End Type
Public Declare Function FLASH_GetV... | The default marshaling for strings is as 8-bit characters, LPWSTR is a Unicode string though. The return type isn't correct either. Fix:
[DllImport("C:\\flash_cntrl.dll")]
public static extern int FLASH_GetVersion(ref FLASH_INFO vVers);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)
public struct FL... |
4,245,783 | 4,247,956 | How to enable a DHCP subnet through DhcpSAPI | I'm writing a module to manage a DHCP server co-located with the service in which the module exists.
I have code in place using the DHCP Server API which is able to create a subnet and add DHCP reservations. What I don't seem to be able to do is actually enable/activate the subnet scope.
I had assumed that DhcpSetSubne... | Have you tried calling DhcpCreateSubnet with the DhcpSubnetEnabled flag set as noted above? Possibly your code already does this - post the part that fails to create and enable the subnet.
Make sure you check all your Windows APIs calls for errors too. Again, some code would help identify what might be failing.
|
4,245,811 | 4,246,030 | Project Euler Problem 17 - What's wrong? | I decided to try project euler problem 17 today, and I quickly wrote a pretty fast code in C++ to solve it. However, for some reason, the result is wrong.
The question is:
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the... | The problem appears to be with this line:
middle = (getDigit(i, 1)) + 8;
You add 8 to this number - presumably to act as an offset into your dictionary2 - but in the following if statements, you have cases where it needs to be 0. Those can never be satisfied unless getDigit would return -8.
Instead of adding your off... |
4,245,850 | 4,245,956 | Abstract object cannot declare | I'm having a problem with abstract/virtual classes, a replication of the problem here:
#include <iostream>
class A
{
protected:
virtual std::string getDateTime() = 0;
virtual void Write(std::string data, bool addDate) = 0;
virtual bool CheckFile() = 0;
virtual bool OpenFile(std::string path) = 0;
v... | It doesn't work that way by default in C++ - You want a diamond inheritance pattern, but in C++ you get separate roots: So BasicClassA and BaseClassB each have their own BaseClassA (vtable and instance variables).
You probably want to use Virtual Inheritance.
For a clearer idea on non-virtual inheritance:
#include <ios... |
4,245,954 | 4,246,231 | using mem_fun() for container of smart pointers | I have recently taken the decision of changing a vector of pointers into a vector of smart pointers, but although these smart pointers are STL-compatible, I could not convert some algorithms to use them.
Consider a
class Base
{
...
virtual bool valid();
};
How do you convert
bool is_any_valid( vector< Base*... | You want to use boost mem_fn, as it does exactly what you want. Look at this link, specifically the PURPOSE section.
http://www.boost.org/doc/libs/1_45_0/libs/bind/mem_fn.html
BTW, you should be passing a reference to const, and not the entire vector in is_any_valid (and your valid() should be const as well).
|
4,245,974 | 4,245,992 | Integration of CPP with Objective C | I want to call a CPP function from Objective C. I have written the function in CPP. I have tried to call the CPP function from test.mm file, but I am getting following error message.
error: 'functionName' was not declared in this scope
I have written the function 'functionName' in testCPP.cpp & testCPP.h
Please help m... | Did you #include "testCPP.h"?
The functions need to be declared in MergeAudioFiles.h, just like in normal C++.
|
4,246,127 | 4,252,305 | Increasing SSL handshaking performance | I've got a short-lived client process that talks to a server over SSL. The process is invoked frequently and only runs for a short time (typically for less than 1 second). This process is intended to be used as part of a shell script used to perform larger tasks and may be invoked pretty frequently.
The SSL handshaki... | After the handshake, you can get the SSL session information from your connection with SSL_get_session(). You can then use i2d_SSL_SESSION() to serialise it into a form that can be written to disk.
When you next want to connect to the same server, you can load the session information from disk, then unserialise it wit... |
4,246,158 | 4,246,223 | Yet another question related to sequence points | Yes i read the article on sequence points. However i could not understand why ++i = 2 would invoke undefined behavior? The final value of i would be 2 regardless of anything, so how come the expression is ub?
code snippet
int main()
{
int i =0;
++i=2;
return 0;
}
Sorry my english is not very good.
| You observe that value will be what you claim, that's how UB can manifest itself among other possible scenarios. The program might output what you expect, output some unrelated data, crash, corrupt data or spend all your money ordering pizza. Once C++ standard says that some construct is UB you should not expect any sp... |
4,246,160 | 4,246,331 | How can I make visual c++ 2010 recognize the declaration "_extension" | While compiling a Visual Studio 2010 program, I included the python2.5 directory. In the file _types.h, there is the code:
#ifndef __off64_t_defined
__extension__ typedef long long _off64_t;
#endif
with the error on extension:
this declaration has no storage class or type specifier.
What is wrong?
| To quote GCC manual:
`-pedantic' and other options cause warnings for many GNU C
extensions. You can prevent such warnings within one expression by
writing `__extension__' before the expression. `__extension__' has no
effect aside from this.
I'd say it's safe to simply ignore it for VC2010. So just define it as n... |
4,246,205 | 4,246,306 | selective access to bits on datatypes with C++ | I'm using C++ for hardware-based model design with SystemC. SystemC as a C++ extension introduces specific datatypes useful for signal and byte descriptions.
How can I access the first bits of a datatype in general, like:
sc_bv<16> R0;
or access the first four bits of tmp.
int my_array[42];
int tmp = my_array[1];
sc_... | For sc_bv, you can use the indexing operator []
For the int, just use normal bitwise operations with constants, e.g. the least significant bit in tmp is tmp & 1
|
4,246,246 | 4,246,274 | winsock server trouble shooting | Ive written and compiled a server program that is meant to echo onto the the screen whatever the client application types in, the code is as below.
/*Server */
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
using namespace std;
const int winsock_version... | Immediately after you accept the new socket into new_fd, you call closesocket on it (below). You should not do that until you are done receiving. If you want to close the listener socket at this point, you should be calling closesocket(sock_fd) instead.
int new_fd;
new_fd = accept(sock_fd, (struct sockaddr*)&i... |
4,246,253 | 5,235,808 | C++ BoundsChecker followup | We've been running for years with BoundsChecker for Visual C++ 6 (I think it was BoundsChecker 5 or 6, too). We've upgaded to VS2008 (finally!), and now need a follow-up for the outdated BoundsChecker.
How's the landscape?
What tools are out there?
Any new kids in town?
Any new ideas dealing with the problems we used m... | I have a massive application (here at work), and the new bounds checker 10.5 (supports 64 bit apps now) pretty much works with it. The trick Max is not to turn on all the checker features of devpartner bounds checker at once. Turn on just memory leaks, or turn on just some other feature, then run your app. And by all m... |
4,246,281 | 4,246,484 | When can a memory leak occur? | I don't know what to think here...
We have a component that runs as a service. It runs perfectly well on my local machine, but on some other machine (on both machine RAM's are equal to 2GB) it starts to generate bad_alloc exceptions on the second and consecutive days. The thing is that the memory usage of the process s... | bad_alloc doesn't necessarily mean there is not enough memory. The allocation functions might also fail because the heap is corrupted. You might have some buffer overrun or code writing into deleted memory, etc.
You could also use Valgrind or one of its Windows replacements to find the leak/overrun.
|
4,246,460 | 4,246,990 | How to create x64 version of native console project? | I have a VS2008 solution with several libraries and 4 console apps. All build and run correctly in 32 bit mode. The libraries all build and run in x64 mode in another solution with a C# app and a C++/CLI interface layer.
Now I need to build an x64 flavor of the 4 console apps (functional and unit tests for the librarie... | If you don't get "x64" in the New Platform combo then the x64 C/C++ compilers are not installed. They are not by default (remarkably) unless you started the VS2008 install with the Custom option and turned the option on. Rerun setup.exe to add them, don't forget to rerun the SP1 setup as well. You can double-check b... |
4,246,514 | 4,246,545 | Why does GCC say "named return values no longer supported"? | I accidentally put the opening brace of my function definition after the return statement
int id(int k) return k; { }
But GCC answered with a weird error message
error: named return values are no longer supported
Can anyone please explain what that weird feature might be? I've never heard about it.
| See here - early NRVO implementation by explicit definition of the named return value in the function header.
Native support for NRVO without this extension was added here - GCC 3.1 Release Series.
Brief cut and paste for context:
G++ now supports the "named return
value optimization": for code like
A f () {
A a;
... |
4,246,674 | 4,249,996 | Polish chars in std::string | I have a problem. I'm writing an app in Polish (with, of course, polish chars) for Linux and I receive 80 warnings when compiling. These are just "warning: multi-character character constant" and "warning: case label value exceeds maximum value for type". I'm using std::string.
How do I replace std::string class?
Pleas... | std::stringdoes not define a particular encoding. You can thus store any sequence of bytes in it. There are subtleties to be aware of:
.c_str() will return a null-terminated buffer. If your character set allows null bytes, don't pass this string to functions that take a const char* parameter without a lenght, or your ... |
4,246,675 | 4,247,312 | seeking recommendations for simple in-memory DB *server* (no persistence needed) | Should support multiple connections, preferably via ODBC. The clients will be running as separate processes on the same machine. No need for persistence, as the the clients will handle the persistence elsewhere. The clients are written in C++ if it matters.
The data is quite simple, it is a set of unrelated bi-directio... | Just because of my familiarity with it, I would go with mysql. To use it as an in memory database use memory as the table type. Redis is an in memory NoSql Database that would probably be a perfect fit for this(It runs in memory, with disc writing for persistence only which can be disabled).
|
4,247,083 | 4,248,141 | Using c/c++ library that uses network for iphone app objective c | I am currently evaluating if a c/c++ library may be used for a specific iPhone project of mine. The original library makes heavy use of windows specific code (for example it includes windows.h and winsock.h). I am aware that I will have to rewrite the parts that use windows specific code and replace winsocks with for e... | You should be able to rewrite portions of your C++ library to used BSD sockets instead of the Windows sockets API without any problems.
Apple does not forbid C++ code from accessing the network, however the only networking APIs offered by iOS are in either C (BSD sockets, CoreFundation) or Objective-C (Foundation…), pe... |
4,247,098 | 4,247,145 | what does #include <crtdll/stddef.h> mean? | I am trying to compile the Scintilla control with MSVC++ 2010 Express Edition, and it's quite painful getting it to work right because I need a bunch of files. When compiling SString.h, I noticed this:
#include <crtdll/stddef.h>
I am no C++ programmer, but I do understand what
#include <xxx.h>
means, but what does ... | If I am not mistaken, that is just a relative path. In other words, Visual Studio will look for stddef.h in the crtdll subdirectory of, probably, the root directory of the project.
|
4,247,101 | 4,293,615 | Mixing Boost FOREACH macro and OpenMP parallelization | I currently have a code (in C) with an outer loop that is OpenMP-parallelized (it operates locally on a shared-memory list). I'm rewriting it in C++, and for many things I found the BOOST_FOREACH macro a very nice syntax as loop construct for iterating over a list, array, etc.
My question is: is there a way I can both ... | Copying from the terminal is worth 1 kilowords:
$ g++ a.cpp -I/opt/boost-1.45.0/include -O -fopenmp
a.cpp: In function ‘int main()’:
a.cpp:12: error: for statement expected before ‘if’
|
4,247,113 | 4,247,223 | What is the best way to store node(i).x and node(i).y array values in c++? | I have to process spatial data which are nodes in a graph.What data type /variable type /data structure allows me to access the values of i-th node's x value and i-th node's y value.
| std::vector would do it.
ie
class Node
{
std::vector< NODE > mNodes;
public:
int x, y;
Node& operator( int i )
{
return mNodes[i];
}
}
Now if you have a Node defined as n you can access the ith node stored in that Node as follows:
Node n;
// Populate Node
int x = n( 12 ).x;
int y = n( 14 ).... |
4,247,135 | 4,247,182 | C++ protecting a private char * of a class | I understand the differences of inheritance of public, private, protected with respect to class method / property constucts. However, my question is specifically associated with pointers to null terminated strings..
class MyClass
{
private:
char * SomeValue;
...
...
}
Now, somewhere through processin... | Typically you would return a const pointer to the chars. There is nothing that can stop someone casting the return value to a non const. But C++ isn't designed to defend against malicious coding.
class MyClass {
char* someValue;
public:
const char* get_SafeSomeValue() const {
return someValue;
}
};
|
4,247,236 | 4,247,286 | What is the difference between "UTF-16" and "std::wstring"? | Is there any difference between these two string storage formats?
| std::wstring is a container of wchar_t. The size of wchar_t is not specified—Windows compilers tend to use a 16-bit type, Unix compilers a 32-bit type.
UTF-16 is a way of encoding sequences of Unicode code points in sequences of 16-bit integers.
Using Visual Studio, if you use wide character literals (e.g. L"Hello Worl... |
4,247,336 | 4,248,867 | C++, polymorphism and iterators | I want to have a Storage interface(abstract class) and a set of Storage implementations (SQLite, MySQL, Memcached..) for storing objects of a known class and retrieving subsets from the Storage.
To me the clear interface would be:
class Storable{int id; blah; blah; blah; string type;};
class Storage{
virtual Sto... | If you want a virtual interface for iteration, something like this?
#include <iostream>
#include <iterator>
struct Iterable {
virtual int current() = 0;
virtual void advance() = 0;
protected:
~Iterable() {}
};
struct Iterator : std::iterator<std::input_iterator_tag,int> {
struct Proxy {
int ... |
4,247,501 | 5,460,631 | How to setup native remote debugging? | Everytime I try to setup remote debugging it always results in a world of hurt. What do I need to do, in order to debug my MFC application on a remote machine? I'm using Windows 7, the VM is using Windows XP.
I've got msvsmon running on the remote computer, and I've connected successfully, but the problem I'm having is... | I just haven't been able to solve this successfully. The only work around I have is to install the same version of Visual Studio that I use, and that installs and configures everything I need for remote debugging. It's a massive overkill, but it does the trick.
|
4,247,519 | 4,248,249 | A few questions about Qt pro-file | I want to locate generated Makefile into some another directory and use it from there.
Here is the part of my pro-file:
OBJECTS_DIR = build/Objects-files
MOC_DIR = build/Moc-files
RCC_DIR = build/Rcc-files
# Location of the binary file
DESTDIR = bin
MAKEFILE = build/Makefile
And with last line I got:
make: *** No ta... | As far as I know, you need to run qmake in the directory where you want the Makefile to be generated, so you your case you would have to do
cd build
qmake ../your_project_file.pro
Regarding the location of the files generated by uic, you need to set the UI_DIR variables (or UI_HEADERS_DIR/UI_SOURCES_DIR if you want to... |
4,247,586 | 4,247,843 | Benchmarking using <ctime> and instruction reordering | I've been using, up until now, the traditional way to benchmark concurrent methods, which is to measure the elapsed duration for a number of runs:
template <typename Functor>
double benchmark(Functor const& f, size_t nbRuns)
{
if (nbRuns == 0) { return 0.0; }
f(); // Initialize before measuring, I am not interesti... | This is a tricky question.
What prevents the compiler from
executing time_t end = time(0); before
the loop here ?
Generally, nothing; in fact, even in C++03. Because of the as-if rule, the compiler may emit any code which has the same observable behaviour. That means, if omitting f() doesn't change any specified ... |
4,247,606 | 4,247,650 | c++ return value when try and catch | hi what should I do when WARANING "control reaches end of non-void function" happens ?
my overloaded operator has try and catch and returns *this ; in the try scope.
I'm using Eclipse , G++ is the compiler, UBUNTU linux
NNmatrix & operator*=(const NNmatrix<T> &mtrxB)
{
// A=2*3 B=3*4 return C=2*4
... | You need to make sure all code paths return a value if the function returns anything but void.
If you are handling exceptions internally to this function without rethrowing, why not just return *this; at the end of the function unconditionally, instead of from inside the try block?
EDIT: per @Mark's comment below, si... |
4,247,615 | 4,249,874 | "expected ':', ',', ';', '}' or '__attribute__' before '{' token" in Struct member function | I'm trying to get my prof's overengineered C++ code to compile. This is the code I have:
/**
* Vector class.
* Common mathematical operations on vectors in R3.
*
* Written by Robert Osada, March 1999.
**/
#ifndef __VECTOR_H__
#define __VECTOR_H__
/**
* Vector3
**/
struct Vector3f
{
// coordinates
float x, y... | Are you trying to compile with a C compiler maybe? If you try to compile your C++ code with a C only compiler I think you would get those type of messages.
|
4,247,797 | 4,248,845 | Check for MySQL connection during a loop | Greetings, I have a C++ script that runs indefinitely. Sometimes (rarely), the MySQL connection is lost, so I'd like to implement some logic to reconnect if that ever happens. I know this is easy, but I just want to ensure that it's correct as I'm new to C++.
This is how the connection is established:
const char* my... | Why not use the MYSQL reconnection option to mysql_options?
From http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html) :-
"MYSQL_OPT_RECONNECT (argument type: my_bool *)
Enable or disable automatic reconnection to the server if the connection is found to have been lost. Reconnect has been off by default since MyS... |
4,248,049 | 4,248,519 | How do I implement the [] operator for this structure? | I want to have something like this below:
template <class T>
struct Container{
public:
//[] operator
private:
T containment;
};
the containment is supposed to be an array with any selective number of dimensions as below:
Container<int[20][4]> obj;
Container<int[5][2][6]> obj1;
//etc...
And I want to implement t... | Who thought reference would come into play here? me!
Thanks to Niki Yoshiuchi, The answer in exact framework that I want is as it follows:
template <class T, size_t N>
struct Container {
private:
T containment[N];
public:
T & operator[](size_t index) { return containment[index]; }
};
Container<int[3][3][3],2> obj;
o... |
4,248,170 | 4,248,458 | Is it possible to overwrite the code segment with a normal C++ program under Windows XP? | I'm currently investigating a windows crash dump and the Visual Studio debugger shows me an "illegal instruction 0xC000001D" when opening the dump file. The code position it shows this error shows a disassembly along the following example:
void g(int x) {
00401E80 push ebp
00401E81 mov ebp,esp
... | No, the memory pages that contain code are write protected. This kind of damage could only occur at process initialization time. But the more likely source is soft RAM errors. Ask your customer to run a RAM test program. Consider file damage is the error is repeatable.
|
4,248,300 | 4,251,368 | In a makefile, is a directory name a phony target or "real" target? | According to what I have read about makefiles, a phony target is any target that does not correspond to an actual filename. My intuition says that a directory as a target would be treated the same as a file.
Why is this important? I have a directory as a target in my makefile. when I have it as a prerequisite to m... | Edit: This only applies to GNU make - a fair assumption given the "linux" tag.
Your target is a real target, not a PHONY one. The problem is that the output directory gets updated when you put targets in it so that it is always newer than your target. This means your target will always get built because it is out of da... |
4,248,357 | 4,248,526 | Are there boost::bind issues with VS2010? | I had the following code line which compiles just fine under g++ and Visual Studio prior to 2010.
std::vector<Device> device_list;
boost::function<void (Device&, boost::posix_time::time_duration&)> callback =
boost::bind(&std::vector<Device>::push_back, &device_list, _1);
Where Device is a class, nothing special a... | This is probably because vector::push_back now has 2 overloads through support or C++0x features, making the bind ambiguous.
void push_back(
const Type&_Val
);
void push_back(
Type&&_Val
);
This should work, or use the built-in function suggested in @DeadMG's answer:
std::vector<Device> device_list;
boost::func... |
4,248,372 | 4,248,414 | Custom Debug printf Used at Runtime | For awhile I've used something like the following to do my debugging.
#ifdef DEBUG
# define Log(fmt, ...) printf(("[%s:%d] %s: " fmt "\n"), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__);
#else
# define Log(...)
#endif
This works fine such that when I compile with something like g++ -DDEBUG=1, I g... | Why not take it simple?
extern boolean GLOBAL_LOGGING_ENABLED = false; // you'll need a single definition in any .cpp
#define LOG(fmt, ...) if (GLOBAL_LOGGING_ENABLED) {printf( // etc etc
// at startup read command line and set the flag to true if asked for
Or anything analogous.
|
4,248,479 | 4,248,507 | How to use **test in c++? | How can I use **pointer in c++? When I use *pointer[] I know how to access one element, but how can I access the elements of **pointer?
| The ** notation in C indicates a pointer to a pointer. The elements of a ** element are just single pointers and can be accessed using normal pointer operations.
char value = 'c';
char* pValue = &value;
char** ppValue = &pValue;
char* pAnotherValue = *ppValue;
Getting back to the actual type which is double pointed... |
4,248,573 | 4,248,785 | Correct alternative to a 'mutable function' in c++ | I often have a problem with const correctness when wrapping algorithms in classes in c++. I feel that I want a mutable function, although this is not allowed. Can anyone advise me how to implement classes such as the one that follows?
The following is the code that I want to write.
The function run() should not be... | make run() const, and make m_data and m_completed mutable. This works but is conceptually wrong because run() demonstrably changes data.
Not true, actually. The variables within your class are, in fact, altered but you could never, ever demonstrate this. Calling run() does not change anything that the user is able to... |
4,249,152 | 4,249,262 | Which would be the easiest way to turn folder with C headers into folder with C++ headers? | I am quite abeginner with all that C/C++ coding. Thay say that having C library with all headers turned into C++ in a fashon like:
#ifdef __cplusplus
extern "C" {
#endif
//.. header code
#ifdef __cplusplus
}
#endif
Will make it possibe to esely use practicly any C lib from sources (modified in such way). S... | You only really need to do that if you have prebuilt C library code you are trying to interface your C++ code to.
If you still have the sources and are going to build all that C code yourself, you may find it easier to just submit them to the compiler as C++ code. With some compilers it is as simple as renaming the sou... |
4,249,294 | 4,249,467 | Good replacement for Qt | Is there any replacement for Qt that can be ported on Windows and Linux or good for Linux that supports OpenGL? I have to write OpneGL C++ application and I want to try something better if exists.
| IMHO, if you do c++ GUI applications portable across Windows/Linux/Mac, Qt is your best shot.
Other popular toolkits are wx and GTK.
|
4,249,330 | 4,249,659 | Can i delete the title bar/caption after the window be created? | WS_OVERLAPPEDWINDOW will got a title bar, how can i delete it after it be created?
| Use SetWindowLong with GWL_STYLE flag to remove the WS_OVERLAPPED flag. Then call SetWindowPos with SWP_FRAMECHANGED to notify system that the window style has changed
|
4,249,554 | 4,250,547 | How can the Child window show in parent's non-client area | in word 2010, the ribbon bar is a child of the main window, but it shows in the top of main window (so, over the caption), how can they make child window shows in the parent's caption area?
| Easy to do if you point to the child's value.
|
4,249,873 | 4,250,005 | Textmate c++ compiling errors | When trying to compile a c++ file in textmate (this happens when clicking run), I get an error in a seperate window that says:
Can't find “g++” on PATH.
Theme:
The current PATH is:
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/usr/texbin
/usr/X11/bin
Please add the directory containing “g++” to PATH in TextMate's Shel... | Textmate is telling you that it cannot find the compiler (g++).
You should either move the g++ executable into one of the directories specified in the PATH variable, or add the directory containing the g++ executable to the PATH.
|
4,249,973 | 4,250,025 | This loop is executing more iterations than is expected | I am having problems with the following code. What I expect is for the do-while loop to execute 4 times, once for each line of the text file it is reading in, but in reality is it executing five time, which is resulting in a segfault later in the program. What am I doing wrong here that's causing it to execute the extr... | eof() doesn't return true until getline consumes the end. It doesn't do this until the getline call after reading the last line. You need to check if eof is true immediately after your getline call:
while(true)
{
getline(DeviceList, line);
if(DeviceList.eof())
break;
}
|
4,250,013 | 4,250,601 | Is destructor called if SIGINT or SIGSTP issued? | I have a class with a user-defined destructor. If the class was instantiated initially, and then SIGINT is issued (using CTRL+C in unix) while the program is running, will the destructor be called? What is the behaviour for SIGSTP (CTRL + Z in unix)?
| No, by default, most signals cause an immediate, abnormal exit of your program.
However, you can easily change the default behavior for most signals.
This code shows how to make a signal exit your program normally, including calling all the usual destructors:
#include <iostream>
#include <signal.h>
#include <unistd.h>
... |
4,250,197 | 4,250,220 | Statements completely ignored (as if: omitted by compiler?) | Well I've hit the brick once again.. Again something I don't see the reason it is wrong and have no idea how to make it work:
I have an instance of class Human. The class Human is derived from Object.. The Object class has a vitrual function called "PerformStep". The Human Class overloads this function.
Human class als... | That macro does nothing in this context, it just expands to a pointer to function. To actually call the function, you need an extra pair of parentheses.
myObj->myfunc; // does nothing
myObj->myFunc(); // calls the function
I expect the compiler has optimized this out, so there's no code to be executed or to break... |
4,250,281 | 4,252,166 | Possible memory leak using C++ string | Consider the following C++ program:
#include <cstdlib> // for exit(3)
#include <string>
#include <iostream>
using namespace std;
void die()
{
exit(0);
}
int main()
{
string s("Hello, World!");
cout << s << endl;
die();
}
Running this through valgrind shows this (some output trimmed for brevity):
==16... | Others are correct, you are leaking because you are calling exit. To be clear, the leak isn't the string allocated on the stack, it is memory allocated on the heap by the string. For example:
struct Foo { };
int main()
{
Foo f;
die();
}
will not cause valgrind to report a leak.
The leak is probable (instead o... |
4,250,538 | 4,250,559 | What is the set-like data structure in c++ | I need to use the advantages of delphi sets like "in" in c++, but I don't know if there is a data structure like sets in c++
I know that I may use an array instead, but as I have said I want to use sets advantages like "in", so is there any built in data structure like sets in c++?
If yes, please explain how to use it... | There is a standard library container called std::set... I don't know delphi, but a simple element in set operation would be implemented by using the find method and comparing the result with end:
std::set<int> s;
s.insert( 5 );
if ( s.find( 5 ) != s.end() ) {
// 5 is in the set
}
Other operations might be implemen... |
4,250,671 | 4,250,696 | question about compiled program usage of external libraries | I know this might be a very stupid question but I am new to compiled languages (my domain is mostly scripting languages like PHP, Python or JavaScript).
I am learning C++ for one project where it is the only language I can use.
I wrote a program in Ubuntu 10.10 and then compiled it. I can run the generated binary file ... | You should read a few things about libraries, and particularly what makes the difference between static and dynamic libraries. To quote the basic definitions so you get the point :
A static library, also known as an
archive, consists of a set of routines
which are copied into a target
application by the compiler... |
4,250,692 | 4,250,901 | Low level systems programming with C++ | I have been using C++ for a while now and I began to get interested in lower level system programming like drivers and stuff. Even some kind of primitive operating system could be very interesting project!
I have no clue where I could start. Are there any not-too-challenging things I could get started with and are ther... | Writing Windows device drivers in C++ isn't impossible, there are not many CRT functions that you could use to get you into trouble. The new operator is unusable for example, you don't have to fear a std::bad_alloc. Unless you replace it, that cuts out a rather large swath of standard C++ library classes.
But that's ... |
4,250,784 | 4,250,804 | Getting rid of the command prompt window in win32 | I just built a standard win32 applicaion but when I run it, there is a command prompt
how can I get rid of that cmd window?
I am not using an IDE
I am just using notepad++ to edit
and mingw to compile through the command prompt
I am doing the g++ command to compile
should I use a different one?
thanks
| Try adding -mwindows to your linker flags.
|
4,250,814 | 4,251,026 | How to avoid a set of values (collected in .so callback calls) from pointing to same address? | // compile with: g++ 1.cc -o test -Wall `pkg-config --cflags --libs glib-2.0` -lgthread-2.0
// or g++ 1.cc -o testq -lglib-2.0 -I/usr/include/glib-2.0 -I/usr/lib64/glib-2.0/include/ -lgthread-2.0c
#include <glib.h>
#include <iostream>
#include <string.h>
int counter;
GAsyncQueue *q;
typedef struct MyStruct {
int fo... |
does that
someExternalAPICallTOprocessData()
would fill &processeddata with a fixed
address of data per each call
This is a little difficult to parse, but were it "could someexternalApi(&data) set data to be the same address on each call", then yes, it could. I have no idea what the "someExternalApi..." is, how... |
4,250,889 | 4,250,963 | Best way to draw a cube with smooth edges? Bezier Curve, load a .3ds or other? | I need to make a cube with smooth corners and smooth edges in C++ with OpenGL.
For all I know I have three options: Bezier curves (maybe, is it possible?), a cube with cylinders for edges and spheres for corners or load a .3ds of a cube.
Any ideas?
| You can simulate a cube with smooth lighting by pointing the normals directly out from the center (simulating an 8 cornered sphere). It totally depends on what exactly you are trying to do. Using the above method may be perfectly good enough.
If you want to define a cube with curved corners (up close) then you are ... |
4,251,306 | 4,251,420 | Marshalling simple string in C# | I've totally failed this really simple P/Invoke.
[System.Runtime.InteropServices.DllImport(
"temp.dll"
)]
private static extern System.IntPtr parser_alloc();
[System.Runtime.InteropServices.DllImport(
"temp.dll",
CharSet = System.Runtime.InteropServices.CharSet.Ansi
)]
... | Turns out that I manually had to set the calling convention to cdecl- the default is stdcall.
|
4,251,487 | 4,251,524 | C++ Linked List Segmentation Fault | I'm writing a program as an assignment for school and I though I had worked out all the bugs until I decided to call my copy constructor. The program is interactive (CLI) which basically has two moduals: a .h and .cpp file for the LList class and a .h and .cpp file for the structure of the program and also a 3rd cpp fi... | The initial thing I spot is that it looks like your destroy() function will always segmentation fault if the list is empty:
void FlowList::destroy()
{
Node* ptr = headM;
Node* post = headM->next;
//...
}
If the list is empty, headM is NULL and then you're trying to do headM->next which will always produce a segm... |
4,251,511 | 4,251,624 | If a particular header already included in stdafx.h - do I need to (have to/should to) to explicitly include it in a .cpp file? | If a particular header is already included in stdafx.h - do I need to (have to/should to) to explicitly include it in a .cpp file (which already includes the stdafx.h) ?
| When stdafx is created for you it is typically a precompiled header.
As a precomiled header it will be necessary to add it to any .cpp that is marked to use precompiled headers (normaly any cpp added to the project except for stdafx.cpp)
You don't need to include headers already included in stdafx.h, including it again... |
4,251,608 | 4,251,629 | C++ File Sending Program | So I need to introduce myself to sockets and general network programming. I consider myself fluent in C++, but I basically can build stuff with the basics of C++ (think having only a basic set of legos)
Now I really need to venture forth and expand my lego set to different pieces (pardon the lego metaphor) But socket p... | You should get yourself the boost libraries.
There is no standard socket API for C++ but boost provides one in their ASIO library that will work on multiple platforms (as is the case with all boost libraries).
|
4,251,652 | 4,251,686 | Empty return in Constructor | I expected Visual Studio to give me an error or at the very least a warning, but it gave me neither when I had an empty return in the constructor:
MyObject::MyObject()
{
if (/*some condition*/)
{
//SomeCode
return;
}
// continue with other code
}
I have not seen usage of this so far in... | The standards say:
12.1 Constructors
...
A return statement in the body of a
constructor shall not specify a return
value. The address of a constructor
shall not be taken.
...
It is OK to have return; in a constructor. My understanding is that this was allowed so that the programmer can return early from ... |
4,251,699 | 4,251,718 | Is it okay to use "and", "or" etc. instead of "&&", "||"? | I'm used to the and and or keywords in C++. I've always used them and typing them is fast and comfortable for me. Once I've heard that these aliases are non-standard and may not work on all compilers. But I'm not sure of it, I don't really know if it's true.
Let's assume that I give someone my code, will he have proble... | They are in fact standard in C++, as defined by the ISO 14882:2003 C++ standard 2.5/2 (and, indeed, as defined by the 1998 edition of the standard). Note that they are built into the language itself and don't require that you include a header file of some sort.
However, they are very rarely used, and I have yet to see ... |
4,251,834 | 4,251,847 | read-eval-print loop (REPL) for several languages | I was wondering if there are some recommended read-eval-print loop (REPL) respectively for
(1) C++
(2) C
(3) Java
Thanks!
| C and C++
You can use CERN's cint.
Java
You can use BeanShell, or if you don't care so much about having Java syntax (e.g. your goal is just to make sure the classes do what you want), you can use Groovy, Scala, JRuby, or Jython.
|
4,251,946 | 4,252,165 | What is wrong with this bit-manipulation code from an interview question? | I was having a look over this page: http://www.devbistro.com/tech-interview-questions/Cplusplus.jsp, and didn't understand this question:
What’s potentially wrong with the following code?
long value;
//some stuff
value &= 0xFFFF;
Note: Hint to the candidate about the base platform they’re developing for. If the perso... | Several answers here state that if an int has a width of 16 bits, 0xFFFF is negative. This is not true. 0xFFFF is never negative.
A hexadecimal literal is represented by the first of the following types that is large enough to contain it: int, unsigned int, long, and unsigned long.
If int has a width of 16 bits, the... |
4,251,963 | 4,252,001 | Injected DLL using GDI+ causes Notepad to crash | I have a Visual Studio solution which consists of a DLL and an EXE. My program sets a global WH_CALLWNDPROC hook. The hook procedure is defined by the DLL. I have verified that the DLL gets properly injected into all the processes I am interested in. The DLL exports a few procedures, which are defined in a header file,... | Pretty sure it is the next line
delete &graphics;
that is making your code blow up. delete should only be used if the pointer was obtained by new, here you're giving it something on the stack. Calling delete on a stack allocated variable makes no sense.
To ensure that the Graphics instance is destroyed before Gdiplus... |
4,251,976 | 4,251,994 | C++ using strcpy_s() on a Pointer to char array Pointer | I am to the point I am confusing myself but here is what I have. I have only recently started to familiarize myself with pointers more to a point I feel more comfortable using them, but I am getting an error about the buffer in strcpy_s() being too small.
Please no comments about me using char arrays instead of std::st... | The problem is you are using sizeof which is a compile time construct to determine the runtime length of *communityID. This will essentially resolve down to sizeof(char*). What you want though is the number of bytes / chars available in *communityID. This information needs to be passed along with the value
GetGroupC... |
4,252,150 | 4,252,235 | I need help adding an array to a vector in C++ | I'm following along with the OpenGL Super Bible 5th edition, and they define a vector(vector as in math) as
typedef float M3DVector3f[3];
I'm trying to add an instance of this to an std::vector(the 're sizable array' in c++), however I keep getting an error saying:
array initialization needs curly braces
Full Err... | Arrays cannot be (directly) copied or assigned, and standard containers requires types to be copyable and assignable.
However, you can (and probably should) do this instead:
struct M3DVector3f // a basic vector class
{
float x;
float y;
float z;
};
Which is copyable and just as usable.
|
4,252,334 | 4,253,805 | Interface not registered (0x80040155) on return from COM call | I'm making a synchronous cross-process COM call that executes successfully, but when I check the HRESULT returned it's the aforementioned 0x80040155, or "Interface not Registered" and the out parameter doesn't contain any data.
Is there a way to re-register COM executibles? I'm not even sure that this would fix it, so... | Most COM executables can be registered by running COMserver.exe /regserver
|
4,252,451 | 4,262,133 | Namespace using declaration (bug in GCC/VS2010)? | namespace A{
int i;
}
int main(){
using A::i;
using A::i;
}
VS2010 - compiles fine
gcc (ideone) - compiles fine
Comeau - gives error ""ComeauTest.c", line 10: error: "i" has already been declared in the current scope
using A::i;"
$7.3.3/8 - "A using-declaration is a
declaration and can therefore be u... | The example you refer to is known to be inconsistent. The committee hasn't yet fixed this.
So, is this a bug in GCC and VS2010?
I don't think it's a bug in either of GCC/VS2010/Clang or Comeau. It appears to be a bug in the C++ Standard. In these cases, compile writers have to make up their mind on what is most viab... |
4,252,552 | 4,288,970 | Segmentation Fault when wrapping V8 in a class? | I want to use Google's Javascript Engine V8 in a project, and attempted to write a wrapper class for the engine. Parts of the Code are copied from samples/shell.cc, from the V8 Distribution.
However, it just aborts with a Segmentation fault, and I can't figure out why, although the problem is happening around v8::inter... | Thy to change v8::Context::Scope context_scope(context); from the constructor (line 134) to internal_executeString (before script = v8::Script::Compile(source, name);). That because the destructor of the class v8::Context::Scope exits from the context.
I changed the method addFunction:
void addFunction(const std::stri... |
4,252,822 | 4,318,504 | Why is my PIC not blinking its leds? | I am trying to get started with pic24's, specifically the PIC24FJ64GA002, and I have looked in the datasheet at the registers and whatnot, but I still cannot get it to blink the leds. When I run it via debug it runs correctly, but when I try to actually run it on the pic it seems to not run at all.
I am using an exter... | Thank you guys for all your help, but it was that I set the config bits wrong, when I set them in the config editor in mplab all works well.
Thank you for all your help!
|
4,252,876 | 4,253,023 | what after the basic c++? | i studied basics of c++ in college, we used the book object oriented programming in c++ by robert lafore.
i studied till pointers (almost half the book) and i still feel outdated using the console and not doing something other than that (forgive me for my ignorance) i want to do windows simple apps and knowing how to e... | There are simpler languages to learn programming in then C++, and less complicated concepts to be mastered in simple CLI applications. In fact, using C++ to write GUI software is probably one of the hardest things to learn to do well. If you are intent on learning only visual programming, and only in C++, then I sugg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.