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,984,571 | 6,984,885 | Boost::asio and async_read | I am trying to use Boost::asio and async_read to implement a timeout in protocol which uses the serial port.
I have done a test implementation using synchronous read, which works just find, but my implementation with time out does not work.
void set_result( boost::optional<boost::system::error_code> * a, boost::system:... | Hmm... The problem here is subtle, basically when you cancel the previous timer - another event is triggered on the io_service (a call to the handler responsible for that timer) to indicate it has been cancelled (with the appropriate error_code). Because you are only calling poll_one, the read is good to go, so you han... |
6,984,677 | 6,984,928 | IEEE 754 Float debug - from memory little endian to the actual floating number | I am testing IEEE 754 floating format with VS2008 using the example below:
int main(int argc, char *argv[])
{
float i = 0.15625;
}
I put &i to the VS2008 watch and I see the address is 0x0012FF60 and I can see address's content is 00 00 20 3e from Memory debug window, see below:
0x0012FF60 00 00 20 3e cc cc cc c... | You are printing out something broken. We only need 32 bits, which are:
00 00 20 3E
Your variable in binary:
00000000 00000000 00100000 00111110
Logical value accounting for little endian:
00111110 00100000 00000000 00000000
According to IEEE:
0 01111100 01000000000000000000000
S E - 127 M - 1
So now it's clear:
... |
6,984,867 | 6,987,613 | OpenMP Ordered Parallelization | I'm trying to parallelize the following function (pseudocode):
vector<int32> out;
for (int32 i = 0; i < 10; ++i)
{
int32 result = multiplyStuffByTwo(i);
// Push to results
out.push_back(result);
}
When I now parallelize the for loop and define the push_back part as a critical path, I'm encountering the pr... | You can set the size of the out-vector by calling out.resize() and then set the value by index, not by push_back()
Pseudo-code:
vector<int32> out; out.resize(10);
for (int32 i = 0; i < 10; ++i)
{
int32 result = multiplyStuffByTwo(i);
// set the result
out[i] = result;
}
But, I'd recommend using "classic" arr... |
6,984,994 | 7,770,618 | OpenCV sequences -- how to create a sequence of point pairs? | I'm trying to create an empty sequence (CvSeq) in OpenCV similar in structure to the one returned by, for example, cvHoughLines2 (when used in CV_HOUGH_PROBABILISTIC) - a sequence of point pairs.
I have found a way to make a sequence of (unconnected) points (I hope this is correct for a point sequence):
CvMemStorage *m... | After 20 minutes searching for a solution in order to help, I read the entire question and found a solution edit. Copy and paste, in order to get this question out of unanswered.
Looks like the only thing that needs to be done is to omit the flags completely, indicating that you will not be using any of the predefined ... |
6,984,997 | 6,985,080 | order of two structures | I have these two structures...
typedef struct{
MY_SECOND_STRUCT s1;
}MY_FIRST_STRUCT;
typedef struct{
int s1;
}MY_SECOND_STRUCT;
I prefer this order, I dont want to switch them.
But compiler dont know MY_SECOND_STRUCT at the moment and I get error
error: expected specifier-qualifier-list before 'MY_SECOND... | That order is not possible. You have to switch them.
However, if you declare the member as pointer, then switching is not required:
struct MY_SECOND_STRUCT; //forward declaration is required though
typedef struct{
MY_SECOND_STRUCT * s1; //now its a pointer
}MY_FIRST_STRUCT;
Or, in C++ you can use template as:
t... |
6,985,064 | 6,985,133 | What are defines on different platforms (windows, mac, linux) that can tell your code that is it part of an application, not a library? | So I wonder how my code that can be included into different projects can find out if it is included into library of application? (on Linux, Mac and Windows)
| The simple answer is that it can't. The decision whether an object file
(generated by the compiler) is part of a library or part of the
application isn't made until link time (and aren't libraries part of the
application?).
|
6,985,521 | 6,985,541 | How function overload resoultion takes place in C++? | I am a beginner in C++. I wanted to know, how internally the function overloading takes place in C++
| I recommend you reading C++ Primer. This concept is explained in depth.
On a higher level, function overloading is allowed if both the functions
have same name
declared in the same scope
have different parameter list.
On the lower-level ( inside how compiler figures it out), here's how it is done.
Ther... |
6,985,572 | 6,985,604 | Which is the fastest STL container for find? | Alright as a preface I have a need to cache a relatively small subset of rarely modified data to avoid querying the database as frequently for performance reasons. This data is heavily used in a read-only sense as it is referenced often by a much larger set of data in other tables.
I've written a class which will have ... | For searching a particular value, with std::set and std::map it takes O(log N) time, while with the other two it takes O(N) time; So, std::set or std::map are probably better. Since you have access to C++0x, you could also use std::unordered_set or std::unordered_map which take constant time on average.
For find_if, th... |
6,985,754 | 9,163,322 | SDL_WM_SetCaption not working | any idea why the following code isn't working? Nothing happens when it's called, the window title is still untitled. I'm on Ubuntu linux.
SDL_Init( SDL_INIT_VIDEO );
SDL_WM_SetCaption("Window Title", "Icon Title");
SDL_Surface* screen = SDL_SetVideoMode( 512, 512, 32, SDL_HWSURFACE | SDL_DOUBLEBUF );
Vecto... | Your code may not be at fault. Ubuntu may be responsible for that one. Or rather, the window manager/compositor Compiz that it uses:
https://bugs.launchpad.net/ubuntu/+source/compiz/+bug/257391
Switching from Compiz to Metacity could help you figure out if you are affected by this bug as well.
There may be something ... |
6,985,830 | 6,985,918 | Linux make can't link against Boost non-header only libraries | I successfully switched to Linux, and I really start to love it. Except that I can't link code against Boost libraries that are non-header only.
Steps that I have taken:
Run sudo apt-get install libboost.*-dev in terminal to install the Boost libraries
Let CMake generate my make-files and locate the Boost libraries as... | From your output and your CMakeFiles it doesn't look like you are linking your code to the Boost filesystem library.
That is,
target_link_libraries(RCMeta ${Boost_FILESYSTEM_LIBRARY} ${Boost_REGEX_LIBRARY})
Note: I may have the variable name wrong for that library you may have to double check it.
You can also use the... |
6,986,042 | 6,986,188 | How to draw a triangle with own texture on each corner? | Basically, i want to give 3 textures for each corner of a triangle, and interpolate from one texture to another, just like the colors would be interpolated with glColor() on the corners.
Edit: Since this doesnt seem to be possible via texture combiners, i am willing to do it with shaders.
This is the fragment shader co... | I don't think this is possible without using shaders. In your OpenGl code, I don't see anyway OpenGl could know which texture to affect to each corner. That would require a vertex property (other than color or texture coordinates), which is not possible without shaders.
However, maybe it can be possible with two textur... |
6,986,080 | 6,986,142 | Non-templated container that can hold anything | I have a small framework for working with threads. The main part is an object that is basically a mutex controlled std::queue that one thread pushes onto, and the other thread pops from.
This class cannot be templated, because the types of objects can vary in a single run. Currently, I created a dumb class:
class Objec... | Use std::queue<boost::any>. It will hold objects of any type.
And to get the object, you've to use a special cast function provided by boost itself:
boost::any_cast
|
6,986,151 | 6,986,440 | Explicitly setting the value of a pointer | I am writing a mex-file (using C++) that will accept a memory address as an input, and operate on data at that memory address. Because I am forced to use MATLAB as my environment, my program can only accept MATLAB data types as inputs (char, bool, float, double, and int). How can I go about assigning my input value to ... | What you're trying to do is dangerous because you're passing raw pointers to some C++ code, making assumptions about what exists at that location and executing code based on those assumptions. But let's say you've taken care of all those security issues.
You probably want to pass the pointer to your MEX file as a UINT6... |
6,986,309 | 6,986,366 | difference between cout and write in c++ | I am still confused about the difference between ostream& write ( const char* s , streamsize n ) in c++ and cout in c++
The first function writes the block of data pointed by s, with a size of n characters, into the output buffer. The characters are written sequentially until n have been written.
whereas cout is an obj... | ostream& write ( const char* s , streamsize n );
Is an Unformatted output function and what is written is not necessarily a c-string, therefore any null-character found in the array s is copied to the destination and does not end the writing process.
cout is an object of class ostream that represents the standard outp... |
6,986,751 | 6,986,912 | Loop issues when counting lines in a .csv | It's me again still working on learning how it is possible for me to manage and manipulate .csv files using c++. I've made a small program that creates a new .csv file, fills in the table headings with generic labels, all named "value" for demonstrative purposes.
I then close the file to be sure any changes I made are ... | You made a classic C/C++ error. This line:
else if(x = y)
assigns the value of y to x. It evaluates to true if y is non-zero. What you meant was this:
else if(x == y)
|
6,987,391 | 6,987,511 | Possible reasons for segmentation fault on function exit | What possible reasons can you think of for a segmentation fault on exiting a function in C++? What I mean by that is, that I have a reproducible segmentation fault in a C++ program, and when I investigate using GDB is says
Program received signal SIGSEGV, Segmentation fault.
FooBar (bla=...) at foo.cpp:59
59 }
... | There could be many reasons of this. Run program under Valgrind and most likely it will tell you exact reason or at least will help to investigate and narrow down the problem.
|
6,987,497 | 6,987,704 | const_cast of a static const member | The following code compile well both with GCC (4.2-4.6) and with Clang (2.1), but when I run the executable it gives me "Bus error: 10". I don't understand the reason.
#include <iostream>
struct A
{
static int const v;
A() { ++*const_cast<int *>(&A::v); }
};
int const A::v = 0;
int main(int argc, char * argv[])
... | I think the relevant quote is:
§ 7.1.6.1 (4) from N3242:
Except that any class member declared mutable can be modified, any
attempt to modify a const object during its lifetime results in
undefined behavior.
The examples illustrate the point using const_cast. As James pointed out: the quote can be found in §7.1.5 in ... |
6,988,042 | 6,988,076 | C++: how to build an intersection string of two space separated strings? | I have two space separated strings... (the X doesn't mean the same symbol)
st1 = "abc def kok...."
st2 = "kok bbr def ffe ...."
i would like to construct an intersection string as follows:
common = "kok def"
what is the efficient way to do so in c++?
Thanks
| Use std::set_intersection
Sample program:
I'm assuming you've tokenized your strings already (this solution seems easy to implement).
// Data
std::vector<string> a,b;
a.push_back("abc");b.push_back("kok");
a.push_back("def");b.push_back("bbr");
a.push_back("kok");b.push_back("def");
a.push_back("foo");b.push_back("ffe"... |
6,988,097 | 6,988,129 | Is resizing strings in C++ dangerous | Let's say you have a string like this:
char* a="01234"
Letting &a=0000, &(a+1)=0001, &(a+2)=0002, and so on, what happens if there is some memory already allocated for another variable at 0007, and you try resizing a to a larger size (a="0123456789")? Will a move to a new location that can fit the larger string, or wi... | What you've written isn't C++, and it's definitely not allowed.
Correct way:
const char * a = "01234"; // pointer to array of six const chars.
char b[] = "01234"; // array of six chars
You can only read the values a[0] to a[5], but never change them. You can change the values b[i] for i in 0 to 5, but be sure ... |
6,988,192 | 6,988,334 | Can't get a NaN from the MSVCRT strtod/sscanf/atof functions | Is there any way to get NaNs from the Windows CRT string to float functions?
Why: I'm writing an IEEE float to string converter in C with no information loss (strtod, sscanf or atof return the original float) provided the rounding mode doesn't change.
I'm under MinGW or Visual C++, so these calls go to the MSVC++ runt... | No. They return HUGE_VAL if overflow would occur and 0 if the input can't be parsed or underflow occurs.
|
6,988,367 | 6,988,502 | String At function run time error | Here is a snippet of the code that creates a run time error "Microsoft Visual C++ Runtime Library" http://www.flickr.com/photos/66130188@N07/6023459646/
string text = something;
size_t index = text.find("hoopla");
try{
if(text.at(index-1)<'0'&&text.at(index-1)>'9')
return false;
}catch(out_of_range){return t... | You can avoid the exception check entirely by simply checking the return value of find first:
if ((index == std::string::npos || index == 0) ||
(text[index - 1] < '0' && text[index - 1] > '9') )
{
return false;
}
In the first case, npos, the search string wasn't found, and in the second case it is righ... |
6,988,489 | 6,988,934 | Template partial specialisation | Can somebody explain why are those two specializations indistinguishable to the compiler (gcc 4.5.1 @ ideone)
http://ideone.com/9tNux
template <typename... T> struct S;
template<typename A, typename B, typename... C>
struct S<A, B, C...> {
int f() {return 1;}
};
template<typename... A, typename... C>
struct S< S<A... | My understanding of the issue:
typedef S<S<a, b>, c, d> S2;
Here S<a,b> matches the second specialization better. However, c, d is a better match for the remaining arguments of the first specialization (single arg + list vs list). Hence it is 1:1.
If you comment in B in the second specialization, then the second speci... |
6,988,617 | 6,988,657 | Overloading template classes by template parameter number | Is it possible to have multiple versions of the same class which differ only in the number of template arguments they take?
For instance:
template<typename T>
class Blah {
public:
void operator()(T);
};
template<typename T, typename T2>
class Blah {
public:
void operator()(T, T2);
};
I'm trying to model funct... | The simplest answer would be to have just one template, with the maximum number you want to support and use void for a default type on all but the first type. Then you can use a partial specialization as needed:
template<typename T1, typename T2=void>
struct foo {
void operator()(T1, T2);
};
template <typename T1>... |
6,989,360 | 6,989,410 | c++ simple sum in for loop | i am using g++ (GCC) 4.6.0 and i am having trouble to producing the correct result. given the following simple for loop in c++
void sum(){
int sum;
for(int i=0,sum=0;i<=10;sum+=i,++i);
cout << sum << endl;
}
the output is giving me 0. suppose within the for loop i added
cout << sum << endl;
it give me 0,... | int i=0,sum=0 is not the same as int i=0; sum=0;. It is one statement that declares two variables.
This means that you are shadowing the outer sum:
void sum() {
int sum; // <-- one `sum`
for (int i=0,sum=0;i<=10;sum+=i,++i) {} // <-- second `sum`
cout << sum << endl;
}
Only a declaration statement like that can ... |
6,989,626 | 6,989,643 | Multiple instances of program on multi-core machine | I am assuming a dual-core (2 cores per processors) machine with 2 processors for the questions that follow; so a total of 4 "cores". So some natural questions arose:
Suppose I wrote a simple serial program and built it in, say, Visual Studio.. and ran the same program twice, say, with distinct input data in each run. ... | Which processor they run on is entirely up to the OS and depends on many factors, including whatever else is happening on the same machine. The common case, though, is that they will tend to sit on one core each, occasionally swapping to different cores ("occasionally" may mean several times a second or even more frequ... |
6,989,874 | 6,996,385 | Problems with creating a DirectX 10 device and swap chain | I am having some problems with creating a valid DirectX 10 device and swap chain using D3D10CreateDeviceAndSwapChain. I think it might be my window creation that something goes wrong in since it says that the OutputWindow in the supplied SwapChainDesc is unused=??? (or a random int value)
This problem has been stressin... | I found the problem, I mistyped this line:
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
Should have been:
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
6,989,995 | 6,990,144 | How do I properly use a dynamically-allocated opaque pointer in a scoped pointer class? | Background
I'm working with the Intel IPP Cryptographic Libraries for testing.
They define several opaque structs used for shared contexts over things like hashing and encryption which, of course, cannot be directly instantiated.
To initialize one of these opaque structs, you query for a byte size and then dynamically ... | You are correct that this:
boost::scoped_ptr<IppsSHA256State> ctx(
reinterpret_cast<IppsSHA256State *>(new uint8_t[byteSize])
);
Is a bad idea, for two reasons: delete will be called instead of delete[], and it will be deleting the wrong type.
boost::scoped_array Should work fine:
boost::scoped_array<uint8_t> tem... |
6,990,079 | 6,990,222 | Unexpected result when setting pointers on a hostent struct | I'm sure that it's due to a silly mistake, but I have been debuging during hours and I couldn't solve the issue.
In my program, I have a function that returns the address of a given domain. It calls to getaddrinfo, copies the address to a new dinamically asigned variable, sets its pointer into a hostent struct and retu... | From hostent Structure on MSDN
h_addr_list A NULL-terminated list of addresses for the host.
Addresses are returned in network byte order. The macro h_addr is
defined to be h_addr_list[0] for compatibility with older software.
final->h_addr = (char*)addr;
So the above line is really this
final->h_addr_list[0] = ... |
6,990,135 | 6,990,298 | What other hidden variables (pre-defined using macros) do I have access to in g++? | note: I am using g++ version 4.3.4
So I was learning about assert statements and came across a homebrew assert macro that uses that variables __LINE__ and __FILE__ which (cleverly) give the line number and the file name from where they were called -- in this case, from where the assertation failed. These are epic piec... | As far as getting the function arguments, you can try using __PRETTY_FUNCTION__ instead of __FUNCTION__. More information is available here: http://gcc.gnu.org/onlinedocs/gcc/Function-Names.html
As far as a list of pre-defined macros, you can find a lot of them if you hunt around in here: http://gcc.gnu.org/onlinedoc... |
6,990,173 | 6,990,371 | RValue, template resolution and copy constructors (in Visual C++ 2010) | I'm constructing a simple container class but run into some problems (reassembling the ones in Visual C++ 2010, rvalue reference bug?)
#include <cassert>
#include <utility>
template<typename T0>
class MyType {
public:
typedef T0 value_type;
// Default constructor
MyType() : m_value() {
}
// Element constr... | Your linked question already answers this. Let's define
typedef MyType<float> MF;
typedef MyType<double> MD;
When you say MD t2(t1);, you would like to call the constructor MF::MF(const MD &). However, the constructor template <typename T> MF::MF(T&&) matches better, because it takes T = MD& and thus resolves to MF::... |
6,990,223 | 6,990,332 | Calling a class protected method from a template | I want to have a template that can access the protected method of it's typename parameter. How can I make that work?
For example:
class Foo{
...
protected:
int Bar();
}
template <class T> FooTempl{
...
int SomeMethod(T* ptr) { return ptr->Bar();};
...
}
The reason is that I want the method Foo::Ba... | Add the following line into Foo:
template<typename T> friend class FooTempl;
|
6,990,289 | 6,991,356 | Problem with Gtk::TextView::modify_font when moving from GTKMM 2.4 to GTK3.0 | I have an application that uses gtkmm 2.4 which has worked fine until I recently changed over to gtkmm 3.0. I am having a problem with g++ (version 4.6.1) where it keeps spitting out the error "error: ‘class Gtk::TextView’ has no member named ‘modify_font’". This isn't the case when I revert my build includes back to... | gtkmm 3.0 has override_font() instead of modify_font().
The documentation is indeed somewhat lacking on the details of what has changed in 3.0, and some symbols were renamed without being deprecated in 2.4. I am sure the gtkmm developers would be interested in some help getting the documentation in a better shape, if y... |
6,990,626 | 6,990,647 | Define a string with parts coming from other defines(non strings) | I'm trying to create a version string, which is treated as a char* when used.
I'm currently using
#define VERSION_MAJOR @cmakeproject_VERSION_MAJOR@
#define VERSION_MINOR @cmakeproject_VERSION_MINOR@
#define VERSION_PATCH @cmakeproject_VERSION_PATCH@
#define VERSION_STRING "" VERSION_MAJOR "." VERSION_MINOR "." VERSIO... | Stringification with slingshot should do the trick:
#define QU(x) #x
#define QUH(x) QU(x)
#define VERSION_STRING QUH(VERSION_MAJOR) "." QUH(VERSION_MINOR) "." QUH(VERSION_PATCH)
It'll expand to "1" "." "2" "." "3", which is the same as "1.2.3".
|
6,990,686 | 6,991,889 | c++ Using boost test | How can I convert the following code to use boost unit test framework:
#include <iostream>
#include <fstream>
#include "graph.hh"
int main(int argc, char **argv) {
const char* ifile = argv[1];
Graph gp;
gp.read_xml(ifile);
std::cout << "Checking number of nodes and edges..." << std::endl;
int nodes_expec... | #include <boost/test/included/unit_test.hpp>
#include <fstream>
#include "graph.hh"
using namespace boost::unit_test;
BOOST_AUTO_TEST_CASE( test_num_of_nodes )
{
Graph gp;
gp.read_xml( framework::master_test_suite().argv[1] );
BOOST_MESSAGE( "Checking number of nodes and edges..." );
BOOST_CHECK_EQUAL(16, gp... |
6,990,692 | 6,990,705 | C++ how to pass a boost shared pointer of this instance of class to nested class object? | So we have (pseudo code):
class A
{
A(shared_ptr parent){}
}
class B
{
A *a;
B()
{
a = new A(boost::shared_ptr(this));
}
}
Is it possible to do such thing with shared_ptr in C++ and how to do it in real C++ code?
| You need enable_shared_from_this:
#include <memory>
class B : public std::enable_shared_from_this<B>
{
A * a;
public:
B() : a(new A(std::shared_from_this())) { }
};
(This is for C++0x; Boost should work similarly.)
Just making a shared pointer from this is tricky because you might shoot your own foot off. Inherit... |
6,990,726 | 6,990,768 | Correct way of declaring pointer variables in C/C++ | I noticed some people use the following notation for declaring pointer variables.
(a) char* p;
instead of
(b) char *p;
I use (b). What is the rational behind the notation (a)?
Notation (b) makes more sense to me because character pointer is not a type itself. Instead the type is character and the variable may be a p... | Bjarne Stroustrup said:
The choice between "int* p;" and "int *p;" is not about right and wrong, but about style and emphasis. C emphasized expressions; declarations were often considered little more than a necessary evil. C++, on the other hand, has a heavy emphasis on types.
A "typical C programmer" writes "int *p;"... |
6,990,988 | 6,991,004 | reference variable and pointer problem | I have a pointer which is pointing to an integer variable. Then I assign this pointer to a reference variable. Now when I change my pointer to point some other integer variable, the value of the reference variable doesn't change. Can anyone explain why?
int rats = 101;
int * pt = &rats;
int & rodents = *pt; ... | The line
int & rodents = *pt;
is creating a reference to what pt is pointing to (i.e. rats). It's not a reference to the pointer pt.
Later, when you assign pt to point to bunnies, you would not expect the rodents reference to change.
EDIT: To illustrate @Als point, consider the following code:
int value1 = 10;
int val... |
6,991,259 | 6,991,358 | C/C++ SEH Example build failure | I am complete unfamiliar with c/c++. I need to compile a small program to do some analysis.
This is the program
#include<stdio.h>
#include<string.h>
#include<windows.h>
//#include<seh.h>
#include<excpt.h>
int ExceptionHandler(void);
int main(int argc,char *argv[])
{
char temp[512];
printf("Application launched");... | As @Ajay has pointed out SEH is a feature of the Microsoft C/C++ compiler. So there is little luck in using it with GCC (unless you use some addon support - see my comment at his answer about libSEH - mind you I have not personally used it).
If there is no requirement to use GCC or Dev C++, you could try using the free... |
6,991,453 | 6,991,705 | Rendering mesh polygons in OpenGL - very slow | I recently switched from intermediate mode and have a new rendering process. There must be something I am not understanding. I think it has something to do with the indices.
Here is my diagram: Region->Mesh->Polygon Array->3 vertex indices which references the master list of vertices.
Here my render code:
// Render th... | There is no point in using array rendering if you're only rendering 3 vertices at a time. The idea is to send thousands through with a single call. That is, you render a single "Polygon Array" or "Mesh" with one call.
|
6,991,911 | 6,991,953 | Is there a way to get the range of memory addresses that are available on the heap? | It seems to me that this is how memory works in C++:
If you use new then you are asking the compiler's implementation to give you some memory (any memory) from the heap.
If you use the placement new syntax, the you are asking to re-allocate a specific memory location that you already know the address of (let's just ass... | Not in any portable way. Modern operating systems tend to use paging (aka virtual memory) anyway, so that the amount of memory available is not a question that can be easily answered.
There is no requirement for the memory in the heap to be contiguous, if you need that you are going to have to write your own heap, whic... |
6,992,075 | 6,992,130 | To implement a Shared memory manager in C++ | I have implemented a simple shared memeory code which is scattered in the two processes(1 acts writer and other acts as reader). But I want manage this SHM code(just like a memory manager),which works independent of any reader/writer processes. By simply giving some hooks/pointers to out side, Can any one suggests me a... | An application cannot "share" its memory using plain pointers on a modern operating system. This is something which requires the assistance of the OS, and is highly dependent on the OS in question. For instance, on Linux the best bet would be to use SysV Shared Memory.
Make sure you understand the overhead of multiple ... |
6,992,233 | 6,992,532 | 3D Separating Axis Theorem, what axis to test? | I know I need to project the vertices of my polyhedra on a whole bunch of axes, i've read these axes are the normals to each of the faces of one polyhedra (or is it both?). I've also read i use the cross product of each edge of one collidable with each edge of the other collidable. So lets say i have 2 polyhedra each w... | In short, the only planes you need to check are those that are defined by the faces of your objects; that is, the normal of the faces is the normal of the planes to check. The direction of the normal doesn't matter, since you're just projecting the vertices anyway.
Also note that this only works for convex meshes, and ... |
6,992,329 | 6,992,415 | Issues understanding heap | I have a small understanding problem with the heap in c++.
I have created a small class to convert a Wchar_t-Array to a Char-Array. Here is a part of my convert class:
.h
class ConvertDataType
{
private:
char *newChar;
};
.cpp
size_t i;
char *newChar = new char[wcslen(WcharArray)];
wcstombs_s(&i, newChar, strlen(n... | Your solutions is correct. When you call delete [] then the memory block refer by pointer is set as free but nothing more. Your content will still be there until you allocate another memory in this address block and you overwrite the data. But you cannot rely on reading from deleted memory. Sometimes it works but it is... |
6,992,414 | 6,992,452 | Looking for a stl multimap like container that allows looking for a key by value | I'm in need to lookup the key from a particular element. It doesn't have to be very fast, but it should be better that iterating through all values.
In particular, this is my problem space:
multiple values per key
very fast lookup by key
insertion/deletion speed not important
key lookup from value that does better tha... | Try Boost.Multi-Index.
|
6,992,446 | 6,992,462 | Learn CPP: Split string and manipulation? |
Possible Duplicate:
Remove spaces from std::string in C++
I am starting to learn cpp. Hope you guys can help me. Right now, I am having a problem with strings. I get input from the user and want to ignore the white space and combine the string. Here it is:
getline(cin, userInput);
If user input is: Hello my name is... | You can use:
remove_if(str.begin(), str.end(), ::isspace);
The algorithm only changes the values and not the container contained values, So you need to call string::erase to actually modify the length of the container after calling remove_if.
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
or if y... |
6,992,541 | 6,992,989 | OpenGL rotation in given direction | I'm thinking about an easy way of defining rotations in opengl.
I understood how rotations about any given axis by some amount work. I also know that I can rotate around each axis in turn. But all that doesn't really help my problem.
What I want to do, is rotating an object such that it looks in a certain (given) direc... | You don't have to use glRotate for this. You already figured out you know something, the target direction. But target direction is not everything, you could still rotate the object around the targeting axis, so you need an Up vector, too.
That is the object's local Z axis (or any other matrix you may designate as "forw... |
6,992,550 | 8,779,914 | Using RTTI to determine inheritance graph in C++? | What, if any, c++ constructs are there for listing the ancestors of a class at runtime?
Basically, I have a class which stores a pointer to any object, including possibly a primitive type (somewhat like boost::any, which I don't want to use because I need to retain ownership of my objects). Internally, this pointer is... | I had a similar problem which I solved through exceptions! I wrote an article about that:
Part 1, Part 2 and code
Ok. Following Peter's advise the outline of the idea follows. It relies on the fact that if D derives from B and a pointer to D is thrown, then a catch clause expecting a pointer to B will be activated.
One... |
6,992,593 | 6,992,644 | C++ enum redefenition and C++0x | If I want to exclude problems with enums and type redefinition in C++ I can use the code:
struct VertexType
{
enum
{
Vector2 = 1,
Vertor3 = 2,
Vector4 = 3,
};
};
struct Vector2 { ... };
struct Vector3 { ... };
struct Vector3 { ... };
Is there a way to remove the wrapper above enum.... | How about namespace?
namespace VertexType
{
enum V
{
Vector2 = 1,
Vertor3 = 2,
Vector4 = 3,
};
}
struct Vector2 { ... };
struct Vector3 { ... };
struct Vector4 { ... };
|
6,992,597 | 7,005,493 | Add namespaces in IXMLDOMDocument root element using C++ | I know there is an example in stackoverflow using JS, but I need to accomplish this using C++ and by a strange reason I am not able to add the namespace to the root element using put_nodeValue() if the attribute name is prefixed with "xmlns:".
So, I need something like this:
<entry xmlns="http://www.w3.org/2005/Atom" x... | I got it! I received some help :)
// Create (root) document
hr = CoCreateInstance(
CLSID_DOMDocument30,
NULL,
CLSCTX_INPROC_SERVER,
IID_IXMLDOMDocument,
(void**)&doc);
assert(hr == S_OK);
// Define namespaces
BSTR atomNamespace = L"http://www.w3.org/2005/Atom";
BSTR mediaNamespace = L"http://searc... |
6,992,768 | 6,993,241 | undefined reference when trying to load a custom mysql plugin - how to debug? | I am trying to write my own MySQL storage engine which uses a key-value store as a back-end.
I wrote now my first version which implements the mandatory parts and I am able to compile, link, and install my MySQL source instance. After doing so I tried to load my new plugin with the following command in the mysql consol... | It was a stupid error: the MySQL build system uses the -fno-implicit-templates option. Removing this for my plugin solved the problem (I could also make an explicit instance, but since I program only a prototype this should be ok).
|
6,993,049 | 6,993,071 | Pointer that can point to multiple classes | I'm developing a game. There's a "Player" class and an "NPC" class.
Each instance of these classes can have a "target". That target can be another player or another NPC. I'd like this "target" value to point to the instance of the Player/NPC that the Player/NPC has selected.
So the problem being, with my current setup ... | You can make common base class for Player and NPC. This base class can have common field from Player and NPC or just can be empty (but should have virtual destructor), then you can store pointer of that type.
class Target
{
public:
virtual ~Target(){}
};
class Player : public Target
{
...
};
class NPC : publi... |
6,993,061 | 6,993,787 | Build Qt in "Release with Debug Info" mode? | Is there a way to build Qt in "Release with Debug info" mode ? My application crashes only in "release" mode (works fine in Debug mode) and seems the issue comes from Qt (may be a bug in Qt).So I want to see the debug info of Qt.
Qt docs has "debug" , "release" but not "release with debug" mode.
[Upate]
My application ... | Update: See @milanw's answer below. This is now supported directly in qmake
We use qmake to generate vcproj files to build Qt. I wrote a python script (but sed is fine too) to change the vcproj-files to build with debug information in release too.
Having debug info is indeed invaluable for stack traces that go back an... |
6,993,132 | 6,993,177 | Format specifiers for uint8_t, uint16_t, ...? | If I have an integer variable I can use sscanf as shown below by using the format specifier %d.
sscanf (line, "Value of integer: %d\n", &my_integer);
Where can I find format specifiers for uint8_t, uint16_t, uint32_t and uint64_t?
uint64_t has probably %lu.
| They are declared in <inttypes.h> as macros: SCNd8, SCNd16, SCNd32 and SCNd64.
Example (for int32_t):
sscanf (line, "Value of integer: %" SCNd32 "\n", &my_integer);
Their format is PRI (for printf)/SCN (for scan) then o, u, x, X d, i for the corresponding specifier then nothing, LEAST, FAST, MAX then the size (obviou... |
6,993,400 | 6,993,501 | Managing a singleton destructor | The following small example implements a singleton pattern that I've seen many times:
#include <iostream>
class SingletonTest {
private:
SingletonTest() {}
static SingletonTest *instance;
~SingletonTest() {
std::cout << "Destructing!!" << std::endl;
}
public:
static SingletonTest *get_instance() {
... | ...not exactly a direct answer, but too long for a comment - why not do the singleton this way:
class SingletonTest {
private:
SingletonTest() {}
~SingletonTest() {
std::cout << "Destructing!!" << std::endl;
}
public:
static SingletonTest& get_instance() {
static SingletonTest instance;
return ins... |
6,993,527 | 6,993,605 | C++ MAC OS X cannot write to ~/Library/Application Support/<appname> | If i save files inside the .app bundle, it saves OK, but apple recommends saving files inside the Application Support
under
~/Library/Application Support/appname
or
~/Library/Application Support/bundleid
I tried both, but I am always getting an exception. I am getting a path to the Application Support, which is
/Us... | The directory is not automatically created for you. Before saving the file, you first need to check if the directory exists, and if not, you need to create the directory.
|
6,993,673 | 6,993,944 | How to exclude unused methods from final binary? | I thought that private methods, which are not used inside its class are removed by the compiler/linker and would not be part of the final binary.
I have created an example class, with a private method which is implemented but not used.
class XXX
{
public:
XXX();
private:
void MyUnusedMethod();
};
And in the i... | One portable way is to have a .o file for each function. Then build an archive .a from those .o files. When linking against that archive the linker links in only those .o files that resolve symbols, i.e. the .o files with a function that nobody calls are not linked in.
Another way is to use latest versions of gcc with ... |
6,993,724 | 6,993,770 | C++ Ways to pass a pointer to a temporary object (on the heap) to a function? | I've got a function that takes a pointer to an object of a custom class (actually pointers to a base class such that polymorphism works). Within the calling routine this object however is exclusively needed for the purpose of this call, i.e. is temporary. For example like this:
class A { /** stuff */ };
class B : publi... | The cleanest way is to do
B b;
doSomething(&b);
But what you really should write depends of what the doSomething function does. If it's fine to destruct b at the end of callingRoutine, then it's the faster and cleaner way to do this, because allocating on the stack is faster than new and does not require you to delete... |
6,993,840 | 6,994,009 | Accessing a C++ non-member function from C# via reflection | I need to gain some run-time information about a C++ program, which is kinda difficult due to C++ not offering some sophisticated reflection mechanism. Now, my approach is to compile the C++ code using /clr and to reflect over the resulting assembly from C# (simply because I like that language more than C++).
While thi... | No, it doesn't. You need to learn how C++/CLI works- you can't just recompile a C++ program with /CLR and be done with it. The sc_main method here is native, not managed, and you can't reflect over it, and the same is true about the HelloWorld type, unless you redefined it to be a ref class, but I doubt you did because... |
6,994,114 | 6,994,161 | Can't pass an iterator to a function which accepts pointer | In "Effective STL" tip 16, it says that we should avoid to pass iterator to a function which accepts a pointer. Could anyone explain the detail for me please?
void doSomething(const int* pInts, size_t numInts);
vector<int> v;
...
doSomething(&v[0],v.size()) //correct
doSomething(v.begin(),v.size()) //incorrect
| In some early implementations of the standard library iterators were implemented as pointers.
Code that depended on that property stopped working when iterators became non-pointers.
So, you should not pass an iterator where a pointer is expected, because if it compiles then it's just by happen-chance. An iterator is no... |
6,994,201 | 6,994,221 | Google Protocol Buffers. C++ error: ‘google’ has not been declared | I'm trying to get the following simple C++ program to compile:
#include <stdio.h>
#include <stdlib.h>
using google::protobuf;
int main(void){
printf("Hello\n");
return 0;
}
I keep getting the following error:
error: ‘google’ has not been declared
I've linked to -lproto and have protobuf-compiler and libprot... | You don't include any header which declares the google namespace. You should include the header file generated by the protoc compiler; it pulls in the necessary includes.
|
6,994,354 | 7,081,775 | Ambiguous overload for 'operator<<' with template template arguments | I'm trying to make a template class where one would be able to define the (STL) container used by the class as a template parameter. So I did the following:
template <typename T = float,
template < class, class > class Container = std::vector,
class Alloc = typename std::vector < Spectrum < T > >::a... | Compiles under GCC 4.3 and 4.4, but 4.1 gives an error similar to what you describe. Must be a GCC bug.
|
6,994,506 | 6,994,561 | Google Protocol Buffers. C++ error: 'protobuf' does not name a type | I have the following code which I'm really struggling to compile:
#include <stdio.h>
#include <stdlib.h>
#include "test.pb.h"
using namespace google::protobuf;
using namespace std;
protobuf::RpcChannel* channel; //error on this line!
I keep getting this 'protobuf' does not name a type error. I have no idea how to... | There is no protobuf namespace, since you did using namespace google::protobuf (which you shouldn't). Do namespace protobuf = google::protobuf instead.
|
6,995,039 | 7,005,580 | Registering irrlicht class into angelscript gives <unresolved overloaded function type> | I am attempting to register the following function from Irrlicht, dimension2df:
template <class U>
dimension2d<T>& operator=(const dimension2d<U>& other)
{
Width = (T) other.Width;
Height = (T) other.Height;
return *this;
}
Here is the full source file: http://irrlicht.sourceforge.net/docu/dimension2d_8h_... | I have figured it out, here is the correct code:
r = engine->RegisterObjectMethod("dimension2f", "bool opEquals(const dimension2f &in) const", asMETHODPR(dimension2df, operator==, (const dimension2df&) const, bool),asCALL_THISCALL); assert(r >= 0);
|
6,995,141 | 6,996,601 | Comparing 2 Integers in C++ | I get an error when I try to compare two integers in Qt.
if ((modus==2) & (move != -1))
error: invalid operands of types '<unresolved overloaded function type>' and 'int' to binary 'operator!='
Do I need other operators? I have googled but it seems that Qt uses the same. Thanks for your ansers
| If you're using a C++0x compiler, move might conflict with std::move(). I'm thinking that's what's causing the "unresolved overloaded function type" part of the error message.
|
6,995,148 | 7,004,259 | SDL mute volume in C++ | How can i mute volume with SDL in C++?
The speakers are connected into the headphone jack socket. If volume unmuted i can hear background noise, but when i mute (with 'amixer set Headphone mute') it stops. I tried Mix_VolumeMusic() and Mix_Volume() to set the volume to zero to achieve the same, but it just change the m... | I don't think SDL has a mute function beyond what you're doing, although I'm not even seeing those functions in the documentation on the libsdl.org website. From looking at the API, I'm guessing it just controls an internal software mixer (PCM volume control is in the SDL 1.3 wishlist), but you can check this by adjus... |
6,995,278 | 6,995,319 | default Copy constructer and default assignment operator | what is the difference between either of these used in a code as i have used here.(line 44 ad line 45 both work fine)
Excerpt:
Date temp = *this; //ASSIGNMENT OPERATOR CALL(PROVIDED BY COMPILER)
//Date temp(*this); //COPY CONSTRUCTOR CALL(PROVIDED BY COMPILER)
My Opinion : Is it that during assignment like object1 = ... | Date temp = *this;
Date temp(*this);
Both call copy constructor,
First is called as Copy Initialization & second is called as Direct Initialization.
Simple Rule to remember this is:
If an object is getting created as well as initialized in the same statement then it calls Copy constructor.
If an object is just ass... |
6,995,310 | 6,995,486 | Is volatile bool for thread control considered wrong? | As a result of my answer to this question, I started reading about the keyword volatile and what the consensus is regarding it. I see there is a lot of information about it, some old which seems wrong now and a lot new which says it has almost no place in multi-threaded programming. Hence, I'd like to clarify a specifi... | volatile can be used for such purposes. However this is an extension to standard C++ by Microsoft:
Microsoft Specific
Objects declared as volatile are (...)
A write to a volatile object (volatile write) has Release semantics; (...)
A read of a volatile object (volatile read) has Acquire semantics; (...)
This allows ... |
6,995,460 | 6,995,503 | C++ clang linker problem | I want to do the analysis of debug information of C++ code .
As I understand clang should be able to handle C++.
I tried clang myFile.cpp
But I get
clang: error: unable to execute command: program not executable
clang error: linker command failed due to signal 1 (use -v to see invocation).
Update:
After setting path f... | I think you need to install a linker. GNU ld will be fine; you should be able to install it via your package manager.
Edit: There also is a LLVM linker, less popular, but which would run out of the box with clang once installed (just add it to the PATH a re-run clang.)
|
6,995,541 | 6,995,790 | Create or Change multipage TIFFs | I try to compose new and modify existing multipage TIFFs using Magick++.
Does someone know how I can do this?
I can read a specific page using this code:
Image * img = new Image("path/to/image.tif[0]"); //read page 0
But how can I save changes back to the TIFF? and how can I add new pages?
Google could only tell me th... | I never tried it but what about the writeImages function. Docs are here.
From the docs
Write images in container to file specified by string imageSpec_
|
6,995,572 | 6,995,599 | Using multiple .cpp files in c++ program? | I recently moved from Java for C++ but now when I am writing my application I'm not interested in writing everything of the code in the main function I want in main function to call another function but this other function is in another .cpp file.
Let me explain better if you wouldn't understand:
I have one file: main.... | You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.
other.h
void MyFunc();
main.cpp
#include "other.h"
int main() {
MyFunc();
}
... |
6,995,880 | 6,995,908 | Memory management in C++. | I have the following program:
//simple array memory test.
#include <iostream>
using namespace std;
void someFunc(float*, int, int);
int main() {
int convert = 2;
float *arr = new float[17];
for(int i = 0; i < 17; i++) {
arr[i] = 1.0;
}
someFunc(arr, 17, convert);
for(int i = 0; i < 17; i++) {
... | A segfault occurs when you access a memory address that isn't mapped into the process. Calling delete [] releases memory back to the memory allocator, but usually not to the OS.
The contents of the memory after calling delete [] are an implementation detail that varies across compilers, libraries, OSes and especially d... |
6,995,950 | 6,997,335 | A example in Gotw 67 | There is a example in http://www.gotw.ca/gotw/067.htm
int main()
{
double x = 1e8;
//float x = 1e8;
while( x > 0 )
{
--x;
}
}
When you change the double to float, it's a infinite loop in VS2008.
According to the Gotw explanation:
What if float can't exactly represent all integer values from 0 to
1e8? ... | Well, for the sake of argument, lets assume we have a processor which represents a floating point number with 7 significant decimal digits, and an mantissa with, say, 2 decimal digits. So now the number 1e8 would be stored as
1.000 000 e 08
(where the "." and "e" need not be actually stored.)
So now you want to comput... |
6,995,971 | 6,996,042 | Writing unsigned chars to a binary file using write() | I was making a program that read binary files. So, I read the individual bytes into unsigned chars (actually reading the data as chars and casting them to unsigned chars for each character). Now I have to write back the unsigned chars to the binary file.
The problem is that now I am forced to write individual bytes aft... | You can do the casting on a pointer...
outfile.write((char *)&data[0], data_size);
the same can be done for reading (i.e. just pass a pointer to the first element of an array of unsigned char casting it to a pointer to char).
|
6,996,118 | 6,996,534 | Which is the equivalent header file of MSCorEE.h in mono compiler? | Could someone, please, tell me where to find MSCorEE.h and corerror.h (or equivalents) in mono compiler (Linux systems).
I am trying to compile a code which initiates C# CLR from the native code, it works fine with VC compiler on windows, however, I am not able to find appropriate headers for mono compiler on Linux.
| If I understand correctly you are trying to embed mono in a native application.
You have to do something like this
#include <mono/jit/jit.h>
#include <mono/metadata/environment.h>
#include <mono/metadata/mono-config.h>
#include <mono/utils/mono-logger.h>
#include <mono/metadata/assembly.h>
void InitMonoCrt()
{
m... |
6,996,356 | 6,996,521 | Is there simpler way? | I'd like to know if there is a shorter / simpler way to:
Split the incoming string by words
Write the tokens in reverse order to stdout
There are two restrictions: no libraries and no loops
#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <deque>
void list_st... | Slight abbreviation, we can get rid of a copy thanks to the iterator constructor of deque:
void list_string_elements(std::string s) {
using namespace std;
istringstream iss (s);
deque<string> v(istream_iterator<string>(iss), (istream_iterator<string>()));
copy(v.rbegin(),v.rend(),ostream_iterator<strin... |
6,996,600 | 6,996,740 | In-place destruction on type with overloaded operator-> | Suppose some type Foo has an overloaded operator-> that returns a Bar*:
struct Foo
{
Bar* operator->();
};
If I want to destruct the returned Bar instance in-place from within the Foo class, can I write the following?
this->~Bar();
g++ does not like that code. It works if I write this:
(*this)->~Bar();
Does the ... | Here is the rule for chaining ->, found in 13.5.6 [over.ref] of the standard:
An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).
Since this is a pointe... |
6,996,871 | 6,997,802 | Can Valgrind catch all sorts of undefined behaviour? | In other words can I be sure that my program is undefined behaviour free if it runs without any Valgrind error messages?
| There is a fundamental error here.
Valgrind is not some sort of static analysis tool that understand the semantics of the C++ grammar and thus know when you are invoking Undefined Behavior as specified by the C++ Standard.
Valgrind is a tool that will however alert you whenever you are doing operations in the memory th... |
6,997,194 | 6,999,169 | using declarations and const overloads | Suppose I have two versions of operator-> (overloaded on const) in a base class. If I say
using Base::operator->;
in a derived class, will I get access to both versions or just the non-const one?
| Same business as name hiding. It's all or nothing. Using declarations (7.3.3) bring a name, not a member.
ISO/IEC 14882 (2003), 7.3.3. 1/ A using-declaration introduces a name into the declarative
region in which the using-declaration appears. That name is a synonym
for the name of some entity declared elsewhere.... |
6,997,210 | 6,997,385 | passing this as template argument | I have two classes test1 and test2:
struct test1
{
int r;
test1() {}
test1(int value) : r(value) {}
test1 foo() const;
};
struct test2
{
int r;
test2() {}
test2(int value) : r(value) {}
};
template <typename t>
struct data_t
{
static const t one;
};
template <> const test1 data_t<test1>::o... | When you call a template method with explicit mention of parameters like,
do_somthing<test1, data_t<test1>::one>(); //(1) ok
do_somthing<test1, *this>(); // (2) error
then compiler expects that the explicit arguments should be compile time constants. In your (2)nd case, *this is not resolvable to a compile time const... |
6,997,230 | 6,997,249 | What is the purpose of Signed Char | what is the purpose of signed char if both char and signed char ranges from -127 - 127?
what is the place where we use signed char instead of just char?
|
unsigned char is unsigned.
signed char is signed.
char may be unsigned or signed depending on your platform.
Use signed char when you definitely want signedness.
Possibly related: What does it mean for a char to be signed?
|
6,997,310 | 6,997,423 | Busy Application leads to false "Not responding" state on Windows 7 - WM_UPDATE | During long term operations our C++ Win32 application shows a modal status dialog with a process bar, which is updated irregular every few seconds or so. Starting with Windows 7 we realized that Windows quite soon shows a message " seems to hang..." and/or appends "Not responding" to our window title bar.
We figured o... | Well, the direct answer to your question is that you can call DisableProcessWindowsGhosting().
However, it would be much better to address the root of the problem rather than suppress the symptoms. Your window is being ghosted because you aren't pumping the message queue. You aren't doing that for the admirable reason... |
6,997,372 | 6,997,413 | How to use DLL without header in C++ | Help, please. A have a dll-file. I know it's functions and parameters. How can I use it in Eclipse with MinGW?
| I am assuming you are using windows. In WINAPI you have LoadLibrary and GetProcAddress functions. Here's an example of usage
|
6,997,791 | 6,997,868 | Is inheritance from a base class with no virtual methods bad practice? | I read an answer some time back to a question regarding dynamic_cast. The dynamic_cast failed to work because the base class had no virtual methods. One of the answers said that deriving from classes with no virtual methods generally means a bad design. Is this correct? Even without taking advantage of polymorphism, I ... | It depends what we're talking about:
for Traits classes (no data) it's fine (std::unary_function comes to mind)
for private inheritance (used instead of composition to benefit from Empty Base Optimization) it's fine too
The problem comes when you starts treating such a Derived object polymorphically wrt this Base cla... |
6,998,036 | 6,998,308 | Are there any conventions for printing optional values? | Suppose I want to overload operator<< for an optional<T> class template. How would I print the "absent value", and how would I print a "real value" x?
none
some x
or
[]
[x]
Or should I literally print nothing for the first case and x for the second? How is this normally handled?
| I like the option of print None and Some x. I think that this immediately describes what's going on (especially for people familiar with Haskell).
Personally, I would not use the [] and [x] alternative, because many languages use the square brackets to denote some sort of list. If I were to see that output, I would im... |
6,998,068 | 6,998,515 | Should I write my own data structures to deal with the semantic resolving or using STL directly in a compiler project | I found that STL is so heavy to use, such as vector, string, etc,. As a compiler project, speed and memory are both mattered. So, if I take string as its core data structure, it hard to improve translate speed.
I wander what's your solution to handle strings in your project?
thanks !
| I'd recommend to look into custom allocators for STL if you run into any memory/performance issues (which is not likely to happen in the first place as DeadMG mentioned). I personally use STL with custom memory allocators that again use my own memory manager (so that i can keep track of the memory used by the stl conta... |
6,998,317 | 6,998,754 | c++ Run-Time Check Failure #2 - Stack around the variable 'ToSend22' was corrupted | I have no idea why is that happening - when ever I call this function I have and send TCP messages to the client, I've got this:
Run-Time Check Failure #2 - Stack around the variable 'ToSend22' was corrupted.
Whenever the client is disconnected. ToSend22 is STD string which I am doing
const char *ToSend288 = ToSend22.... | Most probably Client.Send is modifying the char* buffer you are passing to it.
Or other local variable in same function is being overwritten somehow, which is affecting ToSend22 variable. Array or pointer mis-use is definitely involved in this function.
Please post some more code.
|
6,998,369 | 6,998,430 | C++ nested classes accessibility | Given the following code without considering friendship between two classes:
class OutSideClass
{
...
public:
int i_pub;
protected:
int i_pro;
private:
int i_pri;
class InSideClass
{
...
public:
int j_pub;
protected:
int j_pro;
private:
... |
Question 1> Is it true that OutSideClass can ONLY access public members of InSideClass
Yes
Question 2> Is it true that InSideClass can access all members of OutSideClass
No, in C++03. Yes, in C++11.
The Standard text is very clear about this:
The C++ Standard (2003) says in $11.8/1 [class.access.nest],
The member... |
6,998,720 | 6,998,761 | How can I statistic instance numbers of each class and the memory they consumed in the peak time in native C++ project | My compiler project has a serious memory-consuming. So I want to find a method that can find out which class is the worst one. It should give me something like bellow:
--------------------------------------------------------------------
Class name, Instance count, Peak memory consumed
Circle, 223, 2230 k
Rectangle, 1... | Ofcourse I hope you are talking of Dynamically allocated memory.
You should use memory profiling tools.
If not you should overload the new anddelete` operators for your own class and implement the memory count mechanism in the same.
|
6,998,750 | 6,999,978 | Are there cases where a typedef is absolutely necessary? | Consider the following excerpt from the safe bool idiom:
typedef void (Testable::*bool_type)() const;
operator bool_type() const;
Is it possible to declare the conversion function without the typedef? The following does not compile:
operator (void (Testable::*)() const)() const;
| Ah, I just remembered the identity meta-function. It is possible to write
operator typename identity<void (Testable::*)() const>::type() const;
with the following definition of identity:
template <typename T>
struct identity
{
typedef T type;
};
You could argue that identity still uses a typedef, but this solutio... |
6,999,010 | 6,999,068 | What is the difference between these two vector statements? | [!!Correction made to the second code!!]
vector<int> a;
vector<int>*p = &a;
and
vector<int>*b = new vector<int>();
I know that in first scenario, a is on stack and in second b is on heap. But, are there any other differences? Like memory consumed etc.
| Yes vector b is allocated on the heap and vector a is on the stack (assuming the code is in the scope of a method) along with a 4 byte pointer also on the stack. Other differences in memory consumed would depend on the memory manager and how it allocates blocks and any internal bookkeeping required for the heap.
|
6,999,076 | 6,999,744 | Can't show chinese character in Qt-Embedded 4.7.3 | I'm using Qt-Embedded 4.7.3 and trying to show Chinese characters in the widgets.
I've built a x86 version of Qt-embedded so that I can test my application using qvfb. But I can not show chinese due to some unknown reason. Here is a test program I use:
#include <QApplication>
#include <QLabel>
#include <QTextCodec>
in... | I don't know what the problem is, but it's usually better to not include any non-ASCII characters in the code files, but write the code entirely in English and use Qt's internationalization concept (tr, QTranslator, linguist) to translate the Gui.
|
6,999,330 | 6,999,386 | C++ const struct pointer not accessible | I have const struct aiScene *scene; declared in class.
In the function where I define scene = importer.ReadFile(file, aiProcess_Triangulate); , the scene struct is accessible. I can print out scene->mNumMeshes for example.
Problem is that scene is not correclty accessible from another functions. If I try to print out s... | It's impossible to be sure without knowing what's in importer.ReadFile, but a good guess would be that importer.ReadFile returns a pointer to a structure on the stack. After it returns, the structure will quickly get overwritten by other data -- in your first experiment you may just have gotten lucky to get at it befor... |
6,999,845 | 6,999,992 | random_shuffle algorithm - are identical results produced without random generator function? | If a random generator function is not supplied to the random_shuffle algorithm in the standard library, will successive runs of the program produce the same random sequence if supplied with the same data?
For example, if
std::random_shuffle(filenames.begin(), filenames.end());
is performed on the same list of filename... | 25.2.11 just says that the elements are shuffled with uniform distribution. It makes no guarantees as to which RNG is used behind the scenes (unless you pass one in) so you can't rely on any such behavior.
In order to guarantee the same shuffle outcome you'll need to provide your own RNG that provides those guarantees,... |
7,000,594 | 7,001,499 | Why couldn't push_back be overloaded to do the job of emplace_back? | Firstly, I'm aware of this question, but I don't believe I'm asking the same thing.
I know what std::vector<T>::emplace_back does - and I understand why I would use it over push_back(). It uses variadic templates allowing me to forward multiple arguments to the constructor of a new element.
But what I don't understand... | If T has an explicit conversion constructor, there is different behavior between emplace_back and push_back.
struct X
{
int val;
X() :val() {}
explicit X(int v) :val(v) {}
};
int main()
{
std::vector<X> v;
v.push_back(123); // this fails
v.emplace_back(123); // this is okay
}
Making the cha... |
7,000,609 | 7,000,641 | How to support (a = b) = c? | Question 1> what does the following code meaning and what the order of assignment is?
ClassName a1, a2, a3;
a1 = a2 = a3;
Does it mean to First assign value of a3 to a2 and then assign ?? to a1.
Question 2> what does the following code meaning?
ClassName a1, a2, a3;
(a1 = a2) = a3;
Question 3>
Given a class as follo... | Question 1
This:
a1 = a2 = a3;
is equivalent to this:
a1 = (a2 = a3);
For primitive types, or for PODs, this is equivalent to:
a2 = a3;
a1 = a2;
For user-defined types, it's equivalent to:
a1.operator=(a2.operator=(a3));
If you don't define your own overloads of operator=, then this will be the same as for the prim... |
7,000,892 | 7,001,580 | How to find, from which template-layers is object composed of? | How can I use templates, to find out, from which types is type composed of when using template layers?
Let's have
template <typename Super>
class A : public Super {};
template <typename Super>
class B : public Super {};
template <typename Super>
class C : public Super {};
class Blank{};
template <typename Combined... | My attempt (without using C++0x feature(s))
//----------------------------------------
struct null{};
template<typename>
struct split
{
typedef null Ct;
typedef null At;
};
template<template<typename> class C, typename T>
struct split<C<T> >
{
typedef C<null> Ct; //class template
typedef T At; /... |
7,001,034 | 7,001,178 | Problem compiling c++ project using Boost with Clang | I've decided to try out Clang by compiling a c++ project of mine that already compiles under GCC. My project relies on Boost and as a result of including "boost/asio.hpp" clang issues the following error when compiling with the pedantic flag:
lib/boost_1_46_1/mac/boost/date_time/date_generators.hpp:37:30: error: extra ... | Are you giving clang the -pedantic option? It looks like -pedantic is triggering the error. You can always just remove that option.
|
7,001,397 | 7,002,446 | clang llvm intermidiate representation for debug information | Hello I have following c++ code
class classBase
{
public:
int get1(){return 1;}
int get2(){return 2;}
};
class classDer:public classBase
{
public:
int get1(){return 1;}
};
int f()
{
classDer x;
return x.get1();
}
I use following clangExample.cpp -S -emit-llvm -o - command and get
; ModuleID = 'C... | The reason why it is not exported and not even compiled is because functions inside class-declarations are inlined. That means they are only known and compiled inside that particular codefile.
If you would put the class-declaration into a headerfile each .cpp-file would compile the code for the get1() and get2() functi... |
7,001,489 | 7,001,750 | Problem implementing BFS for my graph data struct | Here is design of my graph data structure which i've developed from scratch. Now to implement BFS i am thinking to use some part of STL to levitate more burden.
I am using algorithm from Cormen's book .For some portion of algorithms like
color[u] , distance[u] etc , i am thinking to use map. but i am unable to decide... | Once i was trying to do something similar. The mistake i did was i didn't define the
function object to sort the elements of the map when i stored the pointer to the node as index type. So you should consider this when you design your BFS when keeping the color/other properties as value_type in the map with node pointe... |
7,001,613 | 7,001,877 | Access element of float cv::Mat | I don't understand why I can't get this code to work:
cv::Mat M(2, 3, CV_32FC1);
cv::Point2f center(20, 20);
M = cv::getRotationMatrix2D(center, 20, 1.0);
float test;
test = M.at<float>(1, 0);
test = M.at<float>(0, 1);
test = M.at<float>(1, 1);
The code fails when accessing the elements with M.at. The following assert... | To quote Good Will Hunting, "It's not your fault!"
M has been overwritten with a CV_64C1 or a double rotation matrix and that's why M.at<float>(i,j) fails.
So, don't bother initializing M ; cv::getRotationMatrix will take care of it and return a CV_64F matrix which can (of course) be accessed with M.at<double>(i,j).
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.