Skip to content

Instantly share code, notes, and snippets.

@tetsuok
Created November 29, 2012 16:07
Show Gist options
  • Select an option

  • Save tetsuok/4170042 to your computer and use it in GitHub Desktop.

Select an option

Save tetsuok/4170042 to your computer and use it in GitHub Desktop.
gdb cannot print vector as I hoped (resolved it's because of return value optimization by gcc)
# In RVO, the compiler figures out the local instance of the object to be a return value,
# the compiler allocates the instance directly in the caller context.
#
# See: http://demin.ws/blog/english/2012/04/14/return-vector-by-value-or-pointer/
#
$ g++ -g rvo.cc
rvo.cc: In member function 'std::vector<int, std::allocator<int> > Klass::Func(const std::vector<int, std::allocator<int> >&)':
rvo.cc:16: warning: conversion to 'int' from 'size_t' may alter its value
$ gdb -q a.out
Reading symbols from /work/tetsuo-s/cpp-sandbox/a.out...done.
(gdb) b Klass::Func
Breakpoint 1 at 0x4007a8: file rvo.cc, line 14.
(gdb) r
Starting program: /work/tetsuo-s/cpp-sandbox/a.out
Breakpoint 1, Klass::Func (this=0x7fffffffd94e, v=std::vector of length 3, capacity 3 = {...}) at rvo.cc:14
14 vector<int> temp(v);
(gdb) n
15 for (size_t i = 0; i < v.size(); ++i) {
(gdb) p temp
$1 = std::vector of length 0, capacity -19
(gdb) up
#1 0x00000000004008ae in main () at rvo.cc:27
27 vector<int> ret = k.Func(v);
(gdb) p ret
$2 = std::vector of length 3, capacity 3 = {1, 2, -1}
$ cat weird_vector.cc
#include <vector>
using namespace std;
class Klass {
public:
vector<int> Func(const vector<int>& v);
};
vector<int> Klass::Func(const vector<int>& v) {
vector<int> temp(v);
for (size_t i = 0; i < v.size(); ++i) {
temp[i] -= i;
}
return temp;
}
int main() {
vector<int> v(3);
v[0] = 1;
v[1] = 2;
v[2] = -1;
Klass k;
vector<int> ret = k.Func(v);
return 0;
}
$ g++ -g weird_vector.cc
$ gdb -q a.out
(gdb) b Klass::Func
Breakpoint 1 at 0x100001277: file weird_vector.cc, line 11.
(gdb) r
Starting program: /Users/tetsuo-s/work/cpp-sandbox/a.out
Breakpoint 1, Klass::Func (this=0x7fff5fbff330, v=std::vector of length 3, capacity 3 = {...}) at weird_vector.cc:11
11 vector<int> temp(v);
(gdb) n
12 for (size_t i = 0; i < v.size(); ++i) {
(gdb) p temp
$1 = std::vector of length 0, capacity 0
(gdb)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment