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 |
|---|---|---|---|---|
6,820,330 | 6,820,364 | bug on RELEASE but not on DEBUG | std::string s("foo");
sprintf(buf,"%s",s);
Why at least under MSVC 2010 this line of code doesn't bug in DEBUG, but bug in RELEASE ?
| The %s format specifier expects a NULL terminated char*. You are passing in a std::string instance. If it works in DEBUG, that's just pure luck.
You should use:
std::string s("foo");
sprintf(buf, "%s", s.c_str());
This will extract a char* and ensure that the buffer is NULL terminated.
It is possible that in the runti... |
6,820,407 | 6,830,506 | CUDA streams and context | I am using an application presently that spawns a bunch of pthreads (linux), and each of those creates it's own CUDA context. (using cuda 3.2 right now).
The problem I am having is that it seems like each thread having its own context costs a lot of memory on the GPU. Something like 200MB per thread, so this is really... | Each CUDA context does cost quite a bit of device memory, and their resources are strictly partitioned from one another. For example, device memory allocated in context A cannot be accessed by context B. Streams also are valid only in the context in which they were created.
The best practice would be to create one CU... |
6,820,484 | 6,820,563 | How to structure source code to check in binaries that take a long time to build | I'd like to check in some pre-compiled binaries for 3rd party dependencies. What is a good way to structure my /trunk folder?
My project is has around ten 3rd party libraries in it. My project is also cross-platform. It takes around 1 hour to build everything for just one target. We are getting bigger now and I'd li... | I have done this in a similar way many times. As long as you pre-compile the binaries then check them in to a directory just for them, you're fine no matter where you put it. I personally tend to use "external" rather than "pre-compiled-binaries", but YMMV.
|
6,820,514 | 6,820,533 | c++ stl copy function proper memory management | Just on the following code do I need to allocate memory with new for floatArray or will the copy function allocate memory for me?
Also is it okay to copy a constant vector to an array this way? Why?
vector<float> floatVector;
//filled floatVector here
float *floatArray = new float[floatVector.size()];
copy(floatVecto... | std::copy doesn't allocate memory, you should do it yourself.
|
6,820,615 | 6,820,654 | Can one deallocate memory in a destructor if they allocated memory within a private function in C++? | I am trying to define a class in the global scope which contains some dynamically-allocated arrays. When the class' constructor is called, the program does not have access to user-defined parameters read through a parameter file (i.e. the number of years in a simulation) thus it cannot allocate memory to the proper si... | You have to initialize the value of the instance variable TransferTracker to 0 in the constructor. The problem you're having is the destruction of the Simulation class without actually having assigned dynamic memory to TransferTracker.
Calling delete[] in the destructor with a null pointer is safe. The problem is that ... |
6,820,633 | 6,820,681 | How to make socket chat in C++? | Does anybody know how to make socket chat in C++ using something like sockets in Java? Is there any way to make ip chat in C++?
| yes it is possible. You could use a library like Boos.Asio which has an example of chat in its documentation : http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/example/chat/posix_chat_client.cpp (client part)
|
6,820,678 | 6,820,842 | Problem Initializing an Array in a Global Variables Header File C++ | I'm writing a simple program using SDL, but I'm running into a strange problem. First the code:
#ifndef GLOBAL_VARIABLES_H
#define GLOBAL_VARIABLES_H
#include <string>
#include <cassert>
#include "SDL.h"
#include "SDL_image.h"
using std::string;
const int SCREEN_WIDTH = 800;
const int SCREEN_HEIGHT = 600;
const int ... | First, variable definitions shouldn't be in header files, only extern declarations.
Second, you can initialize variables (including arrays) in the definition, or assign the content as executable statements inside a function. You can't put executable statements at file scope.
Array initialization looks like this:
int ... |
6,820,765 | 6,821,165 | C++ ifstream.getline() significantly slower than Java's BufferedReader.readLine()? | I'm in the process of rewriting one of my Android applications to take advantage of the NDK and one of the first things it has to do every time is open a 1.5MB text file (approximately 150k lines) and put every line in a data structure. When I did this operation using Java's BufferedReader.readLine(), reading the file... | One thought is the stdio synchronization might be slowing you down. That can be turned off. I don't know if that would account for all of the difference, but you could try. Also, you're not using eof() correctly. Finally, I'd use the std::string version of getline()
std::ios::sync_with_stdio(false);
ifstream ifs("/sdca... |
6,821,022 | 6,821,055 | Could a type sensitive language be typeless? | Why is it not possible to make Java or C++ typeless ?
int, float, double etc any type could inherit from a basetype, but why is this not
possible or not applied ?
I could imagine a Java-"typeless" function like this
void some(BASETYPE anyobject, BASENUMERIC a_number) {
for (int i = 0; i < int(a_number); i ++) {
... | Mostly because type-safety is a good thing. It prevents you from calling floating-point functions with characters. It's not a problem; it's a feature which prevents you from shooting yourself in the foot.
|
6,821,134 | 6,835,065 | Implementing IUnknown interface getting error c2259: cannot instantiate abstract class | I'm trying to make an interface that implements the IUnknown interface for my classes to use but I keep getting the above error: c2259: cannot instantiate abstract class. I've tried to implement all 3 methods from IUnknown but alas I still get the error.
Below you can see the code I'm using. This link is my main resour... | Ok, my bad guys... I guess Visual Studios 2010 just sucks because lots of bugs still. It took about 2 dozens builds for it to realize that I had added all the implementation...lol
|
6,821,202 | 6,821,989 | SDL / OpenGL: Implementing a "Loading thread" | I currently try to implement a "Loading thread" for a very basic gaming engine, which takes care of loading e.g. textures or audio while the main thread keeps rendering a proper message/screen until the operation is finished or even render regular game scenes while loading of smaller objects occurs in background.
Now, ... |
Is there any way to share contexts with SDL
No.
Yes!
You have to get the current context, using platform-specific calls. From there, you can create a new context and make it shared, also with platform-specific calls.
Is there any other more "elegant" way to load my data in the background that I may have missed or di... |
6,821,290 | 6,821,846 | C++ global extern "C" friend can't reach private member on namespaced class | Please consider the code:
#include <iostream>
using namespace std;
extern "C"
void foo( void );
namespace A
{
template< int No >
class Bar
{
private:
friend void ::foo( void );
static void private_func( int n );
};
template< int No >
void Bar< No >::pri... | I don't know the explanation, but if you put foo( ) into a namespace, it works.
#include <iostream>
using namespace std;
namespace C
{
extern "C"
void foo( void );
}
namespace A
{
template< int No >
class Bar
{
private:
friend void C::foo( void );
static void p... |
6,821,469 | 6,821,762 | How to prevent SIGPIPE or prevent the server from ending? | A quite standard C++ TCP server program using pthreads, bind, listen and accept. I have the scenario that the server ends (read: crashes) when I kill a connected client.
The reason for the crash is that the write() call on the file fails, thus the program receives a SIGPIPE. And I guess, this makes the server exit.
I t... | Did you by any chance not do the signal ignore prior to spawning off any threads? If you waited until later one of the other threads could still pick up the signal and exit your app.
If that doesn't do it, you can always do a write poll/select before trying the write to make sure the socket is writable.
|
6,821,623 | 6,821,902 | C# COM vs C++ COM return value | I'm building a COM component C#, the customer can set binary data. It would be nice if the COM component returns exception rather than error code, but realized it would be difficult to handle exception in (Delphi, C + + and JScritp). I chose it receives a data in hexadecimal (internally convert to binary) and return in... | You should return an HRESULT from each COM method and return the data in out parameters. However, the COM interop layer shields this from you by automatically translating between COM HRESULT error codes and C# exceptions. I think your code should really look like this:
MIDL
HRESULT getData([out,retval] BSTR* pData);
H... |
6,821,900 | 6,825,132 | variadic function - how to ensure parameters passed correctly | Is there any way (built-in or a code pattern) to ensure that a variadic function is passed the correct number of parameters? (This will be included as part of an API obviously, I can check my own internal code.)
I was considering requiring a UN32 Magic Number to be the last argument passed and check that for validity ... | You could use the PP_NARG macro to add a count semi-automatically.
int myfunc (int count, ...);
#define MYFUNC(...) myfunc(PP_NARG(__VA_ARGS__), __VA_ARGS__)
MYFUNC(a,b,c,d);
MYFUNC(a,b,c,d,e,f,g);
gcc -E produces:
int myfunc (int count, ...);
myfunc(4, a,b,c,d);
myfunc(7, a,b,c,d,e,f,g);
|
6,821,955 | 6,821,981 | I get this error while using std::map. Why? | When I try to compile the following code...
struct MemPages
{
size_t size;
volatile sig_atomic_t acc;
};
typedef std::map<unsigned long, MemPages> PagesMap;
PagesMap pagesMap;
............
pagesMap.insert(pair<unsigned long, MemPages>((unsigned long)addr, memPages ));
............
// This is Line 531
MemPages& mp... | The error says:
invalid conversion from ‘void*’ to ‘long unsigned int’
addr is apparently a void*; the key type of your map is a unsigned long. You need to pass an unsigned long (or, at least something that is convertible to an integer) to operator[].
The casting of a pointer to an integer ((unsigned long)addr) in y... |
6,822,044 | 6,822,081 | Checking if a variable is initialized | Seems like this would be a duplicate, but maybe it is just so obvious it hasn't been asked...
Is this the proper way of checking if a variable (not pointer) is initialized in a C++ class?
class MyClass
{
void SomeMethod();
char mCharacter;
double mDecimal;
};
void MyClass::SomeMethod()
{
if ( mCharact... | There is no way of checking of the contents of a variable are undefined or not. The best thing you can do is to assign a signal/sentinel value (for example in the constructor) to indicate that further initialization will need to be carried out.
|
6,822,154 | 6,822,212 | Function Pointer problems: passing and declaring | Hey i'm trying to figure out Function pointers and how to pass them around/ declare them, but i'm having a little trouble passing a pointer in my Button class constructor and setting it's member function pointer too the passed pointer.
when i write Button(Func1) Button1 it says expected a ';'
when i write Button(Func... | This code has wrong syntax:
Button(&Func1) Button1;
Button(&Func2) Button2;
It should be:
Button Button1(&Func1);
Button Button2(&Func2);
And function pointer declaration:
void (*Func)(void);
Leave without void in parameters:
void (*Func)();
Edit: Working example at ideone.
|
6,822,345 | 6,822,397 | Singleton Template does not compile in Visual C++ |
Possible Duplicate:
Why should the implementation and the declaration of a template class be in the same header file?
I'm currently trying to implement a singleton template. I've taken the code straight from the german Wikipedia (you should be able to read the code). But I always get a weird compile error in Visual ... | Template methods definitions must be available to the end-user of that template. Thus, they (usually) should be in the header file where template is declared. So splitting your template into parts and putting definitions into source (cpp) files results in linker errors.
|
6,822,422 | 6,822,479 | C++: Where to initialize variables in constructor |
Possible Duplicate:
C++ initialization lists
What are the pros/cons of initializing variables at option 1 vs option 2?
class MyClass
{
public:
MyClass( float f, char a );
private:
float mFloat;
char mCharacter;
bool mBoolean;
int mInteger;
};
MyClass::MyClass( float f, char a ) : mFloat( f ), mB... | In short, always prefer initialization lists when possible. 2 reasons:
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, on... |
6,822,681 | 6,822,719 | 'dim': identifier not found | I am getting this error message:
error C3861: 'dim': identifier not found
Here are my includes:
#include "stdafx.h"
#include "HSMBTPrintX.h"
#include "HSMBTPrintXCtrl.h"
#include "HSMBTPrintXPropPage.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
Here is my function:
#define MSS_PORTS_BASE _T("Software\\Microsoft\\... | It looks like you are wanting sizeof:
dwNSize = sizeof(szName);
dwCSize = sizeof(szClass);
sizeof returns the number of bytes of the object/variable. However, I just looked at the documentation for the API RegEnumKeyEx, and it needs the number of characters. So I think it actually should divide by the size of a TC... |
6,822,927 | 7,196,810 | eclipse CDT: rebuilding a dependent project | I'm working on a C++ project with eclipse Indigo + CDT running on linux
It's made of a project for a library, and a project with unit tests for this library.
Obviously the second project depends on the first one.
Both projects use the external builder
But when I modify a header of the first project it does not rebuild ... | If you're used to the latest versions of MS Visual Studio then you should clear off a space on your desk and mark it with a giant 'X' - this enevitably where your fist and maybe even your head will bang in frustration when using eclipse/CDT.
Eclipse has it's own dependency mechanism which does almost nothing, but fortu... |
6,823,184 | 6,823,214 | Having a string how to get its contents from first `/r/n/r/n` until 2 lines from string end? | I try to create simple file upload service in C++. I get all user request body as one big string. User can upload any type of data. I need to get only user file contents from request boby string.
so for example now I have next code working with my service API provider:
std::cout << "Request body: " << request->body << ... | This isn't the most elegant approach, but one option would be to do something like this:
std::string contents = /* ... get the string ... */
/* Locate the start point. */
unsigned startPoint = contents.find("\r\n\r\n");
if (startPoint == string::npos) throw runtime_error("Malformed string.");
/* Locate the end point ... |
6,823,216 | 6,823,280 | C++ using pointers, nothing is passed | Code executes, but nothing gets passed on image_data (line 44 the write_function)
So I have no working array for the function (line 11), why is that so? I thought passing on the reference for image_data should be enough? (I'm used to it, mostly developing JAVA)
#include <iostream>
#include <string.h>
#include <fstrea... | What exactly are you trying to do in this code:
output.write((char*)&image_data,sizeof(image_data));
Array name is a pointer. You're writing to output its content (the memory address), not the actual data it points to. Remove the & operator to write the content it points to, which is what you wanted, I think. Or use &... |
6,823,278 | 6,823,346 | C++: Extend an enum definition? | The Java code by Oracle tends to use constant integer identifiers where the equivalent would be an enum in C++. The nice thing about using the CIIs that you can easily add more in the base class or a derived class and not break the code (too badly...). My question is: Is there a way to achieve this using an enum in C++... | You can do that in Java because it's bytecodes are interpreted (or, more likely recently "Just-in-Time" compiled) : You have separate pieces and they are put together at run-time.
C++ is fully compiled to native code. Any change will require a ful compile. If a full recompile is acceptable, then adding a new item to ... |
6,823,285 | 6,827,455 | How are you debugging C++ for Android NDK? | What are the options for debugging native code on Android? Is gdb the only debugger available? Is their a Visual Studio integration?
I've looked through the Android docs and done the googlesing but am not confident I found the right answer. Hopefully some SO pro's will save me the pain of trial and error.
But if my cho... | I haven't tried this myself, but this blog post explains how to get NDK debugging working in Visual Studio.
Also, I've done a lot of looking into NDK debugging at work, and I haven't seen a mention of using a debugger other than gdb (but please don't take this as a fact, this is just from my experience). I have managed... |
6,823,371 | 6,823,492 | Which version of OpenGL to use? | I currently run a machine that allows me to program in OpenGL 2.1. If I were to make a program, should I use the power of the current OpenGL versions like 3.x/4.x or use 2.1?
On a side question: How can I tell what's the highest version of OpenGL my computer can run?
On another side question: does only upgrading my vid... | OpenGL versions (for AMD and NVIDIA GPUs) roughly correspond to levels of hardware. 2.x OpenGL versions are for DX9-level hardware. 3.x represents DX10-level, and 4.x represents DX11-class hardware. So the version you pick restricts you can run your code.
In general, any AMD or NVIDIA GPU you can actually buy new from ... |
6,823,396 | 6,823,656 | Why might std::vector be faster than a raw dynamically allocated array? | The result of a discussion with a colleague I ended up writing benchmarks to test std::vector vs raw dynamically allocated arrays, and ended up with a surprise.
My tests are as follows:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std... | The difference is not in the performance of the vector compared to the dynamic array, but in the number of accesses to memory that you perform.
Effectively, in the vector test you are re-accessing cached memory, while in the array version you don't. You pay the price of caching the vector version in either case.
In the... |
6,823,727 | 6,823,752 | How can I correctly return a vector with class A elements? | In the underlying example: How can I avoid that the method get_Children will complain that the return type is not correct?
Or in compiler language:
test.cpp: In member function std::vector<A, std::allocator<A> > B::getVector() const:
test.cpp:38: error: passing const Box<A> as this argument of std::vector<T,std::alloca... | Declare Box<T>::get_Children() as const. Because B::getVector() is const, it cannot access a non-const function on a member of B.
|
6,823,853 | 6,823,879 | Programming language to use with MySQL: Java or C++? | I don't know much of either languages, but what would be better for writing applications that deals with the following. Right now, I use PHP, but I'm looking to see what would be the next ideal language to dig into, if the needs arise.
MySQL
off-line data processing of CSV, XML, etc. files
web applications (dynamic we... | If you come from PHP, JAVA is probably a bit easier than C++ for you.
|
6,823,867 | 7,192,833 | Adding custom Destinations in Xcode 4 | I'm trying to use Xcode with an existing project that has a custom build system. It has several different platform targets, and I'd like to be able to specify any one of these and build it easily. All Xcode has to do is run make build-platform DEBUG=1 or something similar.
I've created an External Build System project ... | I have to work with an external Makefile project in Xcode 4, it's 32-bit only. It seems to me the trick to remove the "My Mac 64-bit" item was to set the architecture value (ARCH) to "i386".
In the Info tab I'm setting the makefile options and target:
These changes are really only cosmetic for Xcode's menu items - it... |
6,823,955 | 6,832,383 | PlaySound() mmslib does not play existing sound | EDIT: Solved. Simply the .wav file was not accepted by Windows. I plucked one of Windows own files and renamed it to what my previous file was called and it plays without problem.
I don't know why this can't play the existing file. Windows gives a chime in that something is wrong but I have no clue what.
I added a chec... | This following code perfectly works:
PlaySound(L"C:\\Windows\\Media\\Cityscape\\Windows Balloon.wav", 0, SND_FILENAME );
Adding SND_ASYNC fails to play.
|
6,823,960 | 6,823,974 | Trouble with template method which reads type from a byte array | I have a class that represents some file data. The file contains some headers.
Within the class definition I also have a template method that looks like this
template< typename T>
T Get(int offset)
{
return *((T*)(_data + offset)); // where _data is a member variable. unsigned char*
}
So for example, if I want to ... | Your casts are wrong. You can only do arithmetic on pointers to complete types. Try it like this:
T * const p = reinterpret_cast<T*>(_data);
return *(p + offset);
// or
*(p + offset) = value;
Speaking of, why not implement a single val() accessor for both reading and writing?
T & val(size_t offset) { return *(reinterp... |
6,824,043 | 6,824,121 | Does it make sense to use the move-and-swap idiom on a movable and non-copyable class | If I have a class such as
class Foo{
public:
Foo(){...}
Foo(Foo && rhs){...}
operator=(Foo rhs){ swap(*this, rhs);}
void swap(Foo &rhs);
private:
Foo(const Foo&);
// snip: swap code
};
void swap(Foo& lhs, Foo& rhs);
Does it make sense to implement operator= by value and swap if I don't have a copy ... | Move-and-swap is indeed reasonable. If you disable the copy constructor, then the only way that you can invoke this function is if you were to construct the argument with the move constructor. This means that if you write
lhs = rhs; // Assume rhs is an rvalue
Then the constructor of the argument to operator = will b... |
6,824,265 | 6,824,284 | SIGPIPE, Broken pipe | I am working on a networking program using epoll on linux machine and I got the error message from gdb.
Program received signal SIGPIPE, Broken pipe.
[Switching to Thread 0x7ffff609a700 (LWP 19788)]
0x00007ffff7bcdb2d in write () from /lib/libpthread.so.0
(gdb)
(gdb) backtrace
#0 0x00007ffff7bcdb2d in write () from /... | When you write to a pipe that has been closed (by the remote end) , your program will receive this signal. For simple command-line filter programs, this is often an appropriate default action, since the default handler for SIGPIPE will terminate the program.
For a multithreaded program, the correct action is usually to... |
6,824,488 | 6,824,506 | Is uninitialized data behavior well specified? | Note: I am using the g++ compiler (which is I hear is pretty good and supposed to be pretty close to the standard).
I have the simplest class I could think of:
class BaseClass {
public:
int pub;
};
Then I have three equally simple programs to create BaseClass object(s) and print out the [uninitialized] value o... |
So is this just a case of 'uninitialized data leads to unspecified behavior'
Yes...
Sometimes if you call malloc (or new, which calls malloc) you will get data that is filled with zeroes because it is in a fresh page from the kernel. Other times it will be full of junk. If you put something on the stack (i.e., auto... |
6,824,637 | 6,824,666 | what '< >' means in c++? | I have a tiny question, probably an easy one, but I couldn't found googling it. I am working on some code that has something like that:
Inserter::Inserter(const data::Set& set){
produces<Info>();
}
I don't quite understand what produces means or I am doing something wrong. Here is my interpretation, PLEASE correct me ... | Generics :)
Aka "templates"
I had a class Inserter that had an Inserter object, calling from a
constant of the object set of class data. Then I produces another
object called Info.
Kind of :)
You have a class "Inserter".
It's constructor uses a template class "producer". You instantiate an "Info" kind of "produc... |
6,824,720 | 6,828,779 | How to choose an encryption algorithm to encrypt/decrypt a file? | Recently I am writing a QT program that require me to encrypt/decrypt a file. I am new to encryption where I am totally don't know anything on how to do encryption using programming. After googling a while, I found this thread which is very similar to my objective.
They suggest to use crypto++, but my problem is when ... | Given the explanation of purpose in your reply to my comment on the question, it seems like there's little point going beyond low-level obfuscation of the XML. You could, for example, simply XOR the file content with an arbitrary value (e.g. AA hex), or a small number of values that you use on successive characters (A... |
6,825,052 | 6,825,168 | Passing an argument to a function that gets automatically converted to a pointer | Note: I am using the g++ compiler (which is I hear is pretty good and supposed to be pretty close to the standard).
So, I think I've learned that passing a pointer-to-an-array or passing the actual array as an argument to another function always results in the passing of a pointer-to-that-array.
Similarly, I think I'v... | C doesn't make it possible to pass arrays by value or more generally to copy them (unless by hand). C++ inherits that, so no it is not possible. The better approach would be to use std::array (for C++0x; boost::array is identical and available for C++03), which is a copyable type and can be passed by value.
int i[] = {... |
6,825,186 | 6,825,245 | Convention of using underscores in C++ class member names | The large majority of my programming knowledge is self-taught, so I was never taught proper design patterns, conventions, and so on and so forth.
I've been digging through a lot of my company's software libraries lately, and I notice that a lot of class data members have underscores in their names.
For example:
class I... | It is simply intended to make it clear what variables are members, and which are not. There is no deeper meaning. There is less possibility for confusion when implementing member functions, and you are able to chose more succinct names.
void Class::SomeFunction() {
int imageID;
//...
SetID(imageID + base... |
6,825,196 | 6,825,483 | protocol buffers - store an double array, 1D, 2D and 3D | How can be an array of double (1D) stored using protocol buffer?
What about multi-dimensional (2D or 3D) dense arrays?
| An array of double would be best stored via
repeated double foo = 5 [packed=true];
repeated makes it act as a list, allowing multiple items; packed avoids a header per item.
There is no direct support for rectangular (or higher) arrays in protobuf. The closest is to store something like:
repeated innerType foo = 5; //... |
6,825,205 | 6,825,292 | How do I determine total number of child threads? | I am working on a linux server programming and I am not sure the proper number of child threads for my thread pool. These threads are doing the actual work including parsing and data processing and more. If my server has 8 cores then what is the proper number of child threads that I should spawn? Thanks in advance..
| If you question is about how many threads you actually have, then man ps will give you a number of options for showing the running threads as they were processes -- all you need to do is count them.
If your question is about how many threads you should create, then that entirely depends on your application and what is ... |
6,825,313 | 6,825,340 | "class template has already been declared as a non-class template" | Hey i'm getting this odd error when I leave the namespace sf{ declaration in the later code:
1>c:\libraries and headers\sfml\sfml-1.6-sdk-windows-vc2008\sfml-1.6\include\sfml\graphics\body.h(70): error C2989: 'sf::Body' : class template has already been declared as a non-class template
1>c:\libraries and headers\sfml\s... | The two most likely candidates based on your information are that Graphics.hpp has mismatched { } or that you had a forward declaration of class Body without marking it a template.
|
6,825,375 | 6,825,460 | How is the string type created in c++? | How was the "string" type created in C++? In C, strings are character arrays, but how did C++ turn the character arrays into the "strings" we know of in C++?
| The character array is still in there, it just has a class wrapped around it. Imagine something like this:
class String
{
private:
char* stringData;
public:
String(const char* str)
{
stringData = new char[strlen(str)+1];
strcpy(stringData, str);
}
~String() { delete[] stringData; }
String& opera... |
6,825,376 | 7,067,584 | How to detect memory leaks in QtCreator on Windows? | How can I detect memory leaks in QtCreator on Windows? On the doc, they recommend Memcheck but it only works on Mac and Linux. Any suggestion for Windows?
| After many tries I finally found a method to detect the memory leaks of a Qt project on Windows:
1) First, it cannot be done directly in Qt Creator so you need to create a Visual C++ project to do the memory leak detection. Thankfully, qmake makes this easy. Open the Qt SDK command line tool and run:
qmake -spec win32-... |
6,825,412 | 6,825,522 | Can't use boost::bind to access boost::tuple elements | I'm using the i686-apple-darwin10-gcc-4.2.1 compiler on OSX.6 (I've upgraded a 10.5 install and carried over the previous dev toolkit).
I'm including these libraries in my implementation:
#include <vector>
#include <boost/bind.hpp>
#include <boost/tuple/tuple.hpp>
I have a tuple that looks like this:
typedef boost::tu... | Change
std::equal<unsigned long>
to
std::equal<unsigned long>()
Well, std::equal is a function template, hence the error message. You probably wanted std::equal_to, so use the following:
std::equal_to<unsigned long>()
|
6,825,632 | 6,825,910 | Prefered way to declare pointer/reference variables? | Note: I am using the g++ compiler (which is I hear is pretty good and supposed to be pretty close to the standard).
Not trying to start a grammar war, but just a random question... What is the ideal way to declare a pointer?
int* pI = 4;
int *pI = 4;
(or my favorite, I know it's non-pretty, but I like it):
int*pI = 4... | I prefer
int* a;
int& b;
for the following reason: the type is int* and not int. For me - the type belongs together and needs to stand separate from the name. I know this introduces some problems with
int* a, b;
but that's why I don't declare to variables in one line.
Other than that - like VJo said: stick to the cod... |
6,825,663 | 6,826,279 | c++ private member variable unknown in another function | I have a newbie question about how to assign class member (setter). I am used to scripting and mostly there it's done via (in python)
def set_mymember(mymember):
self.mymeber = mymember
My coworker told me "self" and "this" are not needed in C++ , "this" exists and it's not wrong in this context but that would be... | Can't really tell whats going on without the full code, but I suspect that you're returning a query object from query.build_query that isn't a full copy of the query object, if that makes sense? Can you include the full text of build_query?
Also, I'd make the build_query method void, and not try to assign a fresh Query... |
6,825,720 | 6,825,867 | Using the Windows API to detect IP addresses for network cards and ethernet devices | I would like to write an application to detect the IP addresses of all network connections on a Windows computer system, as well as the IP of all ethernet devices connected to that system. Is there an easy way to do this programmatically with the Windows API?
I'm looking for the C++ equivalent to the answer to this que... | GetAdaptersInfo: retrieves adapter information for the local computer.
DWORD GetAdaptersInfo(
__out PIP_ADAPTER_INFO pAdapterInfo,
__inout PULONG pOutBufLen
);
MSDN for GetAdaptersInfo.
|
6,825,772 | 6,826,146 | Generate Non-Degenerate Point Set in 2D - C++ | I want to create a large set of random point cloud in 2D plane that are non-degenerate (no 3 points in a straight line in the whole set). I have a naive solution which generates a random float pair P_new(x,y) and checks with every pair of points (P1, P2) generated till now if point (P1, P2, P) lie in same line or not. ... | Instead of checking the possible points collinearity on each cycle iteration, you could compute and compare coefficients of linear equations. This coefficients should be store in container with quick search. I consider using std::set, but unordered_map could fit either and could lead to even better results.
To sum it u... |
6,825,801 | 6,826,021 | Is there any other possiblitly to prove this point other than using 'extern' keyword :n3290 draft | A point from ISO draft N3290 :
Unqualified Name Lookup :section 3.4.1, para 14:
If a variable member of a namespace is defined outside of the scope of its
namespace then any name that appears in the definition of the member
(after the declarator-id) is looked up as if the definition of the member
... | Another example which doesn't use extern keyword:
//demo.cpp
int i = 100;
namespace N
{
int i = 200;
struct A
{
static int m;
};
}
int N::A::m = i; //i is 100 or 200?
int main()
{
cout << N::A::m << endl; //what will it print?
}
Output:
200
Online demo : http://www.ideone.com/pRVAb
|
6,826,110 | 6,826,128 | What is the Java equivalent of C++ deque? | in C++ all I had to do was
#include <queue> -> including
queue<int> a; -> defining
a.push(1); ->using
but in java I found very difficult to use simple deque
what should I do...?
more specifically,
How should I code to simply do the same steps
as I did in C++; including, defining, using.
even more specifically,
I wan... | Java has both Queue and Deque types, and a LinkedList, among others, can act as either one:
import java.util.*;
Deque<Integer> q = new LinkedList<Integer>();
q.push(1);
|
6,826,139 | 6,826,520 | Connector/C++ MySQL error code: 2014 , SQLState: HY000 and Commands out of sync error why? | Hi im using Connector/C++ and executing simple 2 sql commands like this :
the first select sql run ok but the second one cause this exception error :
ERR: Commands out of sync; you can't run this comman d now (MySQL
error code: 2014, SQLState: HY000 )
here is the code :
//member of the class
ResultSet *temp_res;... | You can't have more than one active query on a connection at a time.
From the mysql_use_result docs:
You may not use mysql_data_seek(), mysql_row_seek(), mysql_row_tell(), mysql_num_rows(), or mysql_affected_rows() with a result returned from mysql_use_result(), nor may you issue other queries until mysql_use_result()... |
6,826,310 | 6,826,355 | Casting a Boost FileSystem3 iterator to a const char* | I'm looping over some file in a directory using Boost FileSystem 3 and I need to cast the filename to a char* for another lib, Unfortunately my C++ foo is lacking, can anyone help ?
int main(int argc, char* argv[])
{
path p (argv[1]); // p reads clearer than argv[1] in the following code
try
... | The expression*it returns an object of type path, so you've to this:
const std::string & s = (*it).string();
const char *str = s.c_str(); //this is what you want
Or maybe you want to use other conversion functions, as listed below:
const std::string & string() const;
std::string native_file_string() const;
std::strin... |
6,826,402 | 6,830,836 | Why is the size of make_shared two pointers? | As illustrated in the code here, the size of the object returned from make_shared is two pointers.
However, why doesn't make_shared work like the following (assume T is the type we're making a shared pointer to):
The result of make_shared is one pointer in size, which points to of allocated memory of size sizeof(int) ... | In all implementations I'm aware of, shared_ptr stores the owned pointer and the reference count in the same memory block. This is contrary to what other answers are saying. Additionally a copy of the pointer will be stored in the shared_ptr object. N1431 describes the typical memory layout.
It is true that one can ... |
6,826,620 | 6,826,700 | Cast member function for create_pthread() call | I want to stop the warning
server.cpp:823: warning: converting from 'void* (ClientHandler::)()' to 'void ()(void)'
in the call:
pthread_create(th, NULL,
(void* (*)(void*)) &ClientHandler::handle,
(void *) clientHandler);
where handle() is a member function of ClientHandler:
void* ClientHandler::handle();
I ... | You can't do that directly, pointers to member functions are not plain pointers to functions and can't be handed over to C callbacks directly.
You'll need one level of indirection:
void callHandle(void *data) {
ClientHandle *h = static_cast<ClientHandle*>(data);
h->handle();
}
pthread_create(th, 0, &callHandle, st... |
6,826,633 | 6,827,992 | (How) do you handle possible integer overflows in C++ code? | Every now and then, especially when doing 64bit builds of some code base, I notice that there are plenty of cases where integer overflows are possible. The most common case is that I do something like this:
// Creates a QPixmap out of some block of data; this function comes from library A
QPixmap createFromData( const ... | If you can't fix the types (because you can't break library compatibility), and you're "confident" that the size will never get that big, you can use boost::numeric_cast in place of the static_cast. This will throw an exception if the value is too big.
Of course the surrounding code then has to do something vaguely sen... |
6,826,677 | 6,826,828 | Give access to encapsulated container | class X {
public:
typedef std::list<int> Container;
// (1)
const Container& GetElements() const;
// (2)
Container::iterator ElementBegin();
Container::iterator ElementEnd();
// (3)
CustomIterator GetElementIterator();
private:
Container m_container;
};
I'm looking for a cons... | A mix of (2) and (3) would probably be what I'd do :
class X {
public :
typedef std::list<int> ElementContainer;
typedef ElementContainer::size_type ElementSizeType;
typedef ElementContainer::iterator ElementIterator;
typedef ElementContainer::const_iterator ConstElementIterator;
ElementIterator ... |
6,826,683 | 6,826,711 | Load QPixmap from QByteArray in Qt? | I have a byte array with the contents of an image (in png/bmp or some other format).
How can I load it into a QPixmap?
| bool QPixmap::loadFromData ( const QByteArray & data, const char * format = 0, Qt::ImageConversionFlags flags = Qt::AutoColor )
Format here is string literal like "PNG" or something similar
QPixmap p;
QByteArray pData;
// fill array with image
if(p.loadFromData(pData,"PNG"))
{
// do something with pixmap
}
|
6,826,942 | 6,827,081 | Is it possible to write plugin for eclipse other than Java, in Eclipse? | Can anyone help me to write a plugin for eclipse in c++?
@weekens and @celavek thanks for the information. I am going through JNI and will try to implement it.
@celavek: what kind of master/control we have to do? is it riskier to handle in C++ and java interface.
My requirement is to add my own property in Preference ... | The Eclipse framework is written in Java and the whole plugin infrastructure is built around that, which basically means that most of the times you would have to write your plugin in Java(there are other language possibilities to work with the JVM, see comments and the note about Jython below). However there are possib... |
6,826,965 | 6,828,361 | Why does enable_shared_from_this embed a weak pointer instead of embedding the reference counter directly? | The enable_shared_from_this helper contains a weak pointer that is set when creating shared pointer to the object. That means there is the reference-count (allocated separately or together with the object using make_shared) and an extra weak_ptr in the object.
Now why doesn't it simply contain the reference count inste... | The first thing that comes to mind is whether that approach would be feasible at all, and the answer is that it would not:
struct X : enable_shared_from_this {};
std::shared_ptr<X> p( new X );
std::weak_ptr<X> w( p );
p.reset(); // this deletes the object
if ( w.use_count() ) { // this nee... |
6,827,123 | 6,827,215 | Inserting in a vector | unsigned int j = 0;
openListIterator = openListVector.begin ();
while (exitPointDetailsVector[lowestWeightedPointInOpenList.pointId].branchesVector[m].connectedExitPoint >= openListVector[j].pointId)
&& (openListIterator <= openListVector.end()))
{
// Move the iterator.
open... | In the statement openListIterator <= openListVector.end(), if you reach openListIterator == openListVector.end(), then you're going to have a segfault, because when the code reaches openListIterator++, your iterator becomes "out of bound"
Try openListIterator != openListVector.end()
|
6,827,157 | 6,841,712 | how to forbid process termination by regular user? | I cannot implement it as a windows service because my process has to interact with desktop and it's prohibited in Windows 7.
What is the simplest way to accomplish this? Starting under another (privileged) user? How to do this?
My users are not hackers, just an operators, so some "dumb" methods like hiding from task ma... | after long digging I found acceptable answer here: Prevent user process from being killed with "End Process" from Process Explorer
works fine if you're logged in as a regular user, you cannot kill the process from Process Explorer. Admin still can kill it because has sufficient privileges. it's exactly what I needed
|
6,827,185 | 6,827,306 | How can PyImport_AppendInittab fail? | According to the official docs, PyImport_AppendInittab will return -1 on failure. It does not, however, specify why this function would fail.
I'd like to know if it can only fail due to the programmer's fault (incorrect arguments, not being called at the right time, etc), or if it can also fail because of some other fa... | According to the docs, PyImport_AppendInittab() is a convenience wrapper around PyImport_ExtendInittab() and returns -1 "if the table could not be extended". Furthermore, PyImport_ExtendInittab() returns -1 "if insufficient memory could be allocated to extend the internal table". Both functions "should be called befo... |
6,827,496 | 6,827,889 | How to properly use %USERPROFILE% inside code? | Is my code correct? It seems can compile but does not work properly..
CString testing = _T(" --url=") + cstring + _T(" --out=%USERPROFILE%\\snapshot.png");
I want to point it to user's folder..but still cannot work.
| The answer is that you don't use environment variables at all. Rather, you use the shell functions specifically designed to retrieve the path of special folders.
On Windows Vista and later, that function is SHGetKnownFolderPath. It takes KNOWNFOLDERID values to identify the folder whose path you wish to retrieve. In yo... |
6,827,610 | 6,827,768 | When Declaring a Reference to an Array of Ints, why must it be a reference to a const-pointer? | Note: I am using the g++ compiler (which is I hear is pretty good and supposed to be pretty close to the standard).
Let's say you have declared an array of ints:
int a[3] = { 4, 5, 6 };
Now let's say you really want to declare a reference to that array (nevermind why, other than the Bjarne says the language supports ... | int*& ra = a;
int* is a pointer type, not an array type. So that's why it won't bind to a, which has type int[3].
int* const& ra = a;
works, because it is equivalent to
int* const& ra = (int*)a;
That is, a temporary pointer is conceptually created on the right-hand side of the assignment and this temporary is then b... |
6,827,998 | 6,828,191 | Design pattern for multiple output formats | I have a class structure which represents (internally) the data I wish to output to a file.
Some of the member variables are private to the data class so that it can manage itself and stop things going awry.
I then want this data to be output into a number of file formats. I could do something like
savefile_formatA(D... | Depending upon the complexity of your data class you may wish to use a Visitor pattern. If you have some kind of nested data structure then Visitor may well be what you need.
If formatting is something relatively simple, for example you are producing variations on something such as a comma separated list then you can ... |
6,828,049 | 6,828,066 | Problem using static variable in a static function | i have a full static class, using a std::map
thats the simplified case
.h
#ifndef KEYBOARD_H
#define KEYBOARD_H
#include <map>
class Keyboad {
static std::map<char, bool> pressed;
static void keyPressedEvent(char _key);
};
#endif
.cpp
#include "Keyboard.h"
void Keyboard :: keyPressedEvent(char _key... | You need to define the pressed map in your .cpp file:
#include "Keyboard.h"
std::map<char, bool> Keyboard::pressed;
// The rest as before
|
6,828,094 | 6,828,127 | Unique ID with ::InterlockedIncrement (VC++) | Using VC++, to get a unique ID that counts upwards, I was wondering whether this is legal in a multi-threaded application?
uint32_t GetNewId() { return ::InterlockedIncrement(&lastId); }
Basically, I am wondering whether InterlockedIncrement just protects the increment, or whether the return value is also guarded agai... | Yes, that is legal - the access which consists of
read, then
increment, then
write, then
return the incremented value to the caller
will be atomic. Just don't forget that it's 32 bit and can overflow.
|
6,828,170 | 6,828,491 | Java Book or Website (like Cplusplus.com) for C++ programmers to learn java very fast | I am looking for a book which teaches Java very fast. Basically I am a C++ programmer and do not need to know each and every aspect of programming. I am learning java for android apps development. A lot of books like thinking in Java, learning java and others suggested are pretty big and I want something small to get ... | I love to think of the javadoc as the equivalent of cplusplus.com. The comments on standard classes are much more detailed than stl comments are (and the code is a lot easier to read, too)
Personally I'd recommend just reading a tiny bit of literature and then using an IDE that provides really quick access to code and ... |
6,828,359 | 6,828,449 | How to draw clothoids graphically in Qt? | I am trying to build an application which the user can use to draw clothoids with the mouse, i.e. to set the start point and the end point of the spiral and then by dragging these points with the mouse he could also set the shape of the clothoid by modifying the start and end curvature. Probably for changing the curvat... | The best approach would probably be to use the Graphics View Framework.
There are a few examples that should help you getting started in the Graphics View Examples page. The Diagram scene one looks like a good starting point for what you want to achieve.
|
6,828,543 | 6,828,650 | Template class specialization dependent on constructor arguments? | I am investigating a problem with C++ class templates. One class template is specialized but the compiler does not always choose to use the specialization. I found that the constructor arguments seem to influence this:
temlate <class T>
class MyClass { /*some constructors*/ };
template<>
class MyClass <int>
{ void fo... |
But my question is simply this: Is it possible, that constructor
arguments influence the choice of the compiler? How?
No, because you are telling it which type you want to use :
MyClass<int> test1;
test1.foo(); //works
is always creating objects of the specialized type.
|
6,828,576 | 6,828,830 | Why do optimisation flags cause linker errors for some template functions? | I have a problem where an app compiles fine in debug mode with all optimization turned off.
But the moment I compile for release it prints out unresolved link errors.
The functions in question are the following:
template <typename T>
T & Block::val(size_t offset)
{
return *(reinterpret_cast<T*>(_data + offset));
... | You normally wouldn't put template implementations in a .cpp but rather a .h or .inl which is included from a .h, it could be that the debug build of the .o is more liberal with the symbols it exports.
Run nm on the debug and release builds of the .o and diff the symbols.
Templates are unusual in linkers because of the... |
6,828,739 | 6,841,729 | how to start separate process under system account from a windows service? | I've read a lot of similar questions on SO but haven't found an answer
I need to run a separate process from a windows service in logged in user's session but under system account, thus user cannot terminate the process
I need this process to interact with desktop for supervising purposes.
the main goal is to prevent u... | actually there's much simpler way to achieve the same: to prevent process termination by user w/o special privileges (like admin rights)
after long digging I found acceptable answer here: Prevent user process from being killed with "End Process" from Process Explorer
works fine if you're logged in as a regular user, yo... |
6,828,811 | 6,828,890 | Including headers just for private data in a .h file | I have a class defined in class.cpp and class.h. The class uses some structures/classes/types/whatever defined in stuff.h (and of course, stuff.cpp) for private members and methods. My main program is in main.cpp, which #includes class.h, but doesn't care about anything in stuff.h. If it makes a difference, class.cp is... | You do that in C++ by using pImpl aka Opaque Pointers where the class you expose only have one attribute which is a partially defined struct (sometimes people uses void* instead, but to same efefct).
The partially defined struct, then is fully defined inside your stuff.cpp and everything works as you expect -- the only... |
6,828,863 | 6,828,900 | type safe programming languages..? | Could people please rank some programming languages like C,C++,Java,perl etc on benchmark line of type-safe,not-type-safe,weak-typed,strong-typed,static-typed,dynamic-typed,strict-typed etc. Also, if these terms overlap, please let me know.
| I am assuming you are looking for this: http://en.wikipedia.org/wiki/Comparison_of_programming_languages#Type_systems
|
6,828,892 | 6,829,034 | Problem for template class<class_name> that has bitset as argument | I want to write a class in C++ in which one of the parameter is a bitset<size>.
I want to give the facility to vary this "size" for any object of that class but should be constant for that object.
If I make a variable const int size; and initialize it in the constructor, then it does not compile because to writiting bi... | No, there is no other method, because the code for actual instantiation for bitset<N> is generated at compile time, so you have no possibility to delay providing its size until runtime. You have to use the non-type template parameter.
If it was possible, the creators of standard C++ library would have done this and it ... |
6,829,078 | 6,829,108 | C/C++ functions returning NaN in MonoTouch when p/invoked | I have two source files:
File.h:
class Numbers
{
public:
int Get10();
int Get192();
float GetFloat();
};
File.cpp:
int Numbers::Get10()
{
return 10;
}
int Numbers::Get192()
{
return 192;
}
float Numbers::GetFloat()
{
return 3213.1294124f;
}
extern "C"
int Get10()
{
Numbers n;
return... | Maybe changing the return type of this function to float is the way to go?
extern "C"
int GetFloat()
{
Numbers n;
return n.GetFloat();
}
|
6,829,172 | 6,829,625 | Set double[] from float* in initialization list | I have a class that looks roughly like this:
template<std::size_t dim>
class Foo {
public:
Foo(void const * const data);
private:
double vals[dim];
}
For the constructor, I know that void* data points to an array of float values (of dimension dim). Now I would like to initialize the vals-array (preferably) in... | If you're afraid that passed pointer is not aligned to float boundary (for example, file mapping etc), then you can write something like
template<std::size_t dim>
class Foo {
public:
Foo(void const * const data)
{
float temp[dim];
memcpy( &temp, data, dim * sizeof( float ) );
std::copy( ... |
6,829,269 | 6,830,918 | Error Using CvMoments to calculate the HU moments | I am doing my FYP and I am a bit new to both OpenCV and C++. I have looked for info regarding CvMoments and all i found (in theory examples that work) do not solve my problem. I want to load a set of images ("1.png" to "5.png") and write the HU moments into a text file. The code is as shows:
CvMoments moments;
CvHuMome... | You are calling it right, but I suspect that your problem is that the previous call is failing:
IplImage* image = cvLoadImage(filename);
You need to check the result of cvLoadImage() and make sure that you are passing a valid argument to cvMoments():
IplImage* image = cvLoadImage(filename);
if (!image)
{
cout << "c... |
6,829,576 | 6,829,633 | Why does unique_ptr have the deleter as a type parameter while shared_ptr doesn't? | The std::unique_ptr template has two parameters: the type of the pointee, and the type of the deleter. This second parameter has a default value, so you usually just write something like std::unique_ptr<int>.
The std::shared_ptr template has only one parameter though: the type of the pointee. But you can use a custom d... | Part of the reason is that shared_ptr needs an explicit control block anyway for the ref count and sticking a deleter in isn't that big a deal on top. unique_ptr however doesn't require any additional overhead, and adding it would be unpopular- it's supposed to be a zero-overhead class. unique_ptr is supposed to be sta... |
6,829,592 | 6,829,631 | TryEnterCriticalSection | I'm not sure if I correctly understand. TryEnterCriticalSection is called only once, it's not stick like EnterCriticalSection?
E.g. if I write something like
if(TryEnterCriticalSection (&cs))
{
//do something that must be synh
LeaveCriticalSection(&cs);
}
else
{
//do other job
}
//go on
and if TryEnterCriticalSection... | You guessed right. TryEnterCriticalSection() is called once, and tries to enter the critical section only once. If the critical section is locked, it returns false after the check.
In general, if a function returns a boolean or an int, the if/else clauses behaves like following:
if (function()) //function() is called o... |
6,829,774 | 6,829,850 | c++ append a struct into a binary file | I have my struct:
struct a
{
int x;
float f;
double d;
char c;
char s[50];
};
and I wish append each time into my timer schedule into a binary file.
// declaration
std::ofstream outFile;
// constructor:
outFile.open( "save.dat", ios::app );
// tick:
outFile << a << endl;
but inside the save.dat ap... | What you're currently doing is writing the address of the struct definition.
What you want to do is use ostream::write
outfile.write(reinterpret_cast<char*>(&myStruct), sizeof(a));
This will work as long as your struct is a POD (Plain Old Data) type (which your example is). POD type means that all members are of fixed... |
6,829,791 | 6,830,060 | Templated operator overload trick | Is there a way to by using some metaprogramming trick make situation like this works:
int* get();//this fnc returns pointer to int OR nullptr
int k = 1;
//this is the operator which is supposed to compare value and pointer
template<class T>
bool operator!=(const T& left, const T* right)
{
if (right)
{
r... | As already mentioned in other answers that you cannot have operator != for non userdefined types like int, char and so on.
One option is to wrap int inside your user defined struct and achieve the goal.
struct Int
{
int i;
// define all the necessary operators/constructor who deal with 'int'
Int(int x) : i(x) {}
... |
6,830,079 | 6,830,138 | Which method is better for implementing get/set? | There are two methos for implementing get/set.
Method 1:
Define get and set separately.
class my_class
{
// ...
};
class main_class
{
public:
my_class get_data() const
{
return m_data;
}
void set_data(my_class value)
{
m_data = value;
}
private:
my_class m_data;
};
Note: In this method get... | You should always use a reference for any custom classes to pass just the address not the value class. You should also avoid passing back a non-const reference for editing. See below for my recommendations.
class my_class
{
// ...
};
class main_class
{
public:
const my_class & get_data() const
{
return m_da... |
6,830,176 | 6,830,205 | What is the meaning of NULL != value in C++? |
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
I was going through a piece of C++ code and came across a code like
if (NULL != threadInfo)
{
...
...
}
I was just wondering is there any difference between using the expression
if (threadInfo != NULL)
{
...... | No, there is no difference. In case of == there might be some difference. The thing is that if you accidentally write = instead of == the compiler will give an error in the first case.
if (threadInfo = NULL) //always false. The compiler will give you a warning at best
if (NULL = threadInfo) //Compiler error
I persona... |
6,830,459 | 6,830,525 | C++ Novice regarding Vectors and for/while loops | I’m trying to make something that will take lines of input from the user, separate them into strings in a vector, then print them one at a time (8 per line).
so far this is what I’ve got:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int main(void)
{
using namespace std;
vector<st... | Something like this:
for(int i = 0; i < svec1.size(); i++)
{
cout << svec1[i];
if ((i+1) % 8 == 0)
cout << endl;
else
cout << " ";
}
?
EDIT:
the solution above outputs extra space/newline at the end. It can be avoided by something like this:
for(int i = 0; i < svec1.size(); i++)
{
if (i... |
6,830,485 | 6,841,846 | Type error switching from .m to .mm | I encountered this error:
cannot convert 'V_DTLPROMO_BTN_FN_T' to 'V_DTLPROD_BTN_FN_T' in argument passing
in code line:
[ m_vPromoDetails changeButton : V_DTLPROMO_BTN_2 btnFn : V_DTLPROMO_BTN_FN_ADD ];
Both arguments are of type V_DTLPROMO_BTN_T & V_DTLPROMO_BTN_FN_T which is are enum declared in the .h file. Th... | V_DTLPROD_BTN_FN_T is an enum declared in another class.My detailpromo class was somehow getting confused by that enum in detailprod class.I noticed that the function names were same in both the classes ,so I tried to change the function name from changeButton to changeButtonForPromo.That did the trick and errors were ... |
6,830,936 | 6,831,078 | Reading text from file to unsigned char array | I was looking to use OpenSSL to encrypt text in a file, and will need the text to be in an unsigned char array before I encrypt it. What is the easiest way read text from a file to an unsigned char array?
| Your question is tagged both C and C++ (which isn't constructive). I will give an answer for C++.
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
ifstream in("filename.txt"); //open file
in >> noskipws; //we don't want to skip spaces
//initialize a vecto... |
6,830,957 | 6,831,114 | Controlling different apps (Adobe Reader,Word,Windows Media Player,Powerpoint,etc) from C++ code | I am just about to finish my final degree project. I am creating a system that reads a gesture from the Microsoft Kinect and then it makes some actions. So now I'd like to include some interaction with some famous applications.
For example, I'd like to "tell" the Adobe Reader (that has the focus) to go to the next page... | There are generally only a few "acceptable" solutions to problems like this:
Simulate user input
Programatically send keystrokes and mouse clicks
Pros: Compatible with most GUI programs you can think of
Cons: Kludgy, not good at handling any kind of unexpected behavior (i.e. error dialogs). Have to know which windows ... |
6,831,057 | 6,831,253 | Several questions with QtCreator | I'm working on a project which should have GUI written in Qt. I'm thinking using QtCreator as a development IDE, but there are some problems I'm facing. The project should have a dll file which shouldn't be dependent on any qt library/module, it should use only winapi and it should be compiled with both x86 and x64. So... | You can use Qt Creator as pure C++ IDE. It supports generic project (qtcreator project), cmake and qmake.
Using generic project, you have to define all of your make scripts. I don't recommend this.
Using cmake you can do many things as i heard but i don't have any experience on that.
Using qmake your project depends o... |
6,831,094 | 6,831,310 | Ambiguous overload for operator+ | There is polynomial class in Boost math library: Boost polynomial class. I want to expand abilities of this class by adding new functions and I use inheritance as follows:
#ifndef POLY_HPP
#define POLY_HPP
#include <boost/math/tools/polynomial.hpp>
template <class T>
class Poly : public boost::math::tools::polynomial... | This is not possible as far as I know, you'll need something like
template <class T>
Poly<T> operator + (const Poly<T>& a, const Poly<T>& b) {
return Poly<T>(static_cast< boost::math::tools::polynomial<T> >(a) +
static_cast< boost::math::tools::polynomial<T> >(b));
}
to disambiguate the call (wh... |
6,831,231 | 6,831,260 | Should programmers use STL or write their own code? | I don't know much about C++ data structures but I am wondering do you (programmers) use STL or write your own code? After all STL is designed for doing tasks like searching, replacing and much more through a list of data.
Someone really don't need to learn much about the linked list, binary search and many more because... | You should use STL, because it is well tested and optimized.
That doesn't mean you shouldn't know how to write these data structures yourself. With that ability under your belt, you will be able to choose the best STL data structure for your application.
|
6,831,256 | 6,831,365 | C++ writing and reading matrices of doubles from a binary file | Here comes a new issue after my previous question :
I've extended the code to perform matrix binary files I/O and when testing a simple write and read operation, I retrieved only the first line of the matrix...
I don't have managed to find my error, here is the new code :
double** bytes_to_matrix_block(std::ifstream& i... | When reading, you forget to reset j to 0 for new lines
while(i < size1 && !iF.eof()) {
// Missing:
j = 0;
|
6,831,261 | 6,831,401 | How create an object of a Class from a string that holds the name of that class? | Let's say I have a string with my class name inside:
mystring = "CDialogChild";
I would like to create an object of the type name written in my string.
I'd like to do something like:
CDialogParent dlg = CDialogParent(mystring);
My new dlg is now created as type CDialogChild and I can use its methods:
dlg.mycdialo... | There is nothing in C++ that will provide you such feature (called Reflection).
However, if your classes are of finite number, you can do some kind of mapping with some factories :
class IClassFactory // base interface
{ public:
virtual ~IClassFactory(){}
}
template< class T >
class ClassFactory {
/* whatever ... |
6,831,275 | 6,831,486 | Visual Studio setup project says build failed, but does not tell the reason why | ------ Starting pre-build validation for project 'CServ Setup' ------
WARNING: All custom dialogs must precede the 'Installation Folder' dialog.
------ Pre-build validation for project 'CServ Setup' completed ------
1>------ Build started: Project: CServ Setup, Configuration: Release-W2k3 ------
Building file 'C:\temp... | In the 'Tools->Options' menu, 'Projects and Solutions->Build and Run' change the value of the 'MSBuild project build output verbosity' to Detailed or Diagnostic, should help you find the problem.
|
6,831,356 | 6,831,540 | Implementing a C++ ThreadLocal | Do anyone know the best way to implement ThreadLocal in C++ whereby we can set and get values passed when neccesary.
I was reading about ThreaLocal in wikipedia and it says;
C++0x introduces the thread_local keyword. Aside that, various C++
compiler implementations provide specific ways to declare thread-local
var... | This is usually a part of whatever the threading library that your OS uses. In Linux, thread local storage is handled with pthread_key_create, pthread_get_specific and pthread_set_specific functions. Most threading libraries will encapsulate this though, and offer a C++ interface. In Boost, it is the thread_specific_pt... |
6,831,369 | 6,831,467 | C++ Multidimensional arrays generating segmentation faults? | I am writing a script which must copy some names into a multidimensional array, print the contents of the array and then deallocate the memory and terminate. The problem I am having is that when I run the script it only prints out the last name entered. Here is what I have done. Any help would be great! Thanks in advan... | You didn't allocate memory for details[used][0] and details[used][1] so it's using whatever random address was in those locations.
Since this is C++ you can use string instead perhaps? std::string **details;. This should work with your existing code, except that it will leak memory.
Better still is to use a vector of v... |
6,831,485 | 6,831,526 | C++ Generate standard constructor | I often find myself writing very simple classes instead of C-style structs. They typically look like this:
class A
{
public:
type mA;
type mB;
...
A(type mA,type mB,...) : mA(mA),mB(mB),... {}
}
Is that a sensible way of doing things? If yes, I was wondering whether there was any third party plugin out there o... | Yes, just use plain aggregates:
struct A
{
type mA;
type mB;
...
};
Usage:
A x = { mA, mB, ... };
An aggregate has no custom constructors, destructor and assignment operator, and it allows for plenty of optimisations. Aggregate initialization with the brace syntax for example usually constructs the members in p... |
6,831,515 | 6,831,740 | how to configure xmlrpc-c abyss server host? | I am using xmlrpc-c library (c++ version) to write a program. I find that there is no way to configure the xmlrpc server's host. I can only configure the port like below. Can anyone tell me how to configure the hostname for this server?
xmlrpc_c::registry myRegistry;
xmlrpc_c::defaultMethodPtr const XMLRPCMethodP(handl... | This is a server, so it listens for connections on the given port on the machine you are running it on. Giving it a hostname does not make much sense. You can, of course, specify a host to connect to on the client, see here. Or you are talking about binding the server to a particular network interface? I don't think th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.